公告
财富商城
积分规则
提问
发文
2019-01-08 14:02发布
傲
I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?
Thanks.
UIKit has a nice addition to NSString, making sizeWithAttributes: a bit lighter:
CGSize titleSize = [title sizeWithFont:titleFont constrainedToSize:contentCellSize lineBreakMode:UILineBreakModeWordWrap];
Here's Stephen's solution in Clozure Common Lisp, when using the Objective C bridge. I came across this post when searching for a solution, and I just rewrote Stephen's version which worked fine for me. Others using Clozure might find this helpful:
(defun string-width (str font) (let* ((dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary font #$NSFontAttributeName ccl:+null-ptr+)) (attr (#/initWithString:attributes: (#/alloc ns:ns-attributed-string) (ccl::%make-nsstring str) dict)) (size (#/size attr))) (ns:ns-size-width size)))
i dont know if you are suppose to use this in cocoa touch. if it is, then:
- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font { NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width; }
wont work.
in cocoa touch, you gotta add coretext framework and import the header and write your code like this:
UIFont *font = [UIFont fontWithName:@"HelveticaNeue-BoldItalic" size:DEFAULT_FONT_SIZE]; // NSLog(@"%@", NSFontAttributeName); NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, (NSString *)kCTFontAttributeName, nil];
but, GEE!!!!!
NSMutableAttributedString *as = [[NSMutableAttributedString alloc] initWithString:self.caption attributes:attributes]; [as size].width;
there's no size this method in NSMutableAttributedString!
finally, this would work
[self.caption sizeWithFont:font].width
as for ios 7 and up this is the correct way:
NSString * buttonTitle = @"demo title"; CGSize stringSize = [buttonTitle sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
最多设置5个标签!
UIKit has a nice addition to NSString, making sizeWithAttributes: a bit lighter:
Here's Stephen's solution in Clozure Common Lisp, when using the Objective C bridge. I came across this post when searching for a solution, and I just rewrote Stephen's version which worked fine for me. Others using Clozure might find this helpful:
i dont know if you are suppose to use this in cocoa touch. if it is, then:
wont work.
in cocoa touch, you gotta add coretext framework and import the header and write your code like this:
but, GEE!!!!!
there's no size this method in NSMutableAttributedString!
finally, this would work
as for ios 7 and up this is the correct way: