How to get the width of an NSString?

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.

10条回答
放荡不羁爱自由
2楼-- · 2019-01-08 14:24

UIKit has a nice addition to NSString, making sizeWithAttributes: a bit lighter:

CGSize titleSize = [title sizeWithFont:titleFont 
                     constrainedToSize:contentCellSize 
                         lineBreakMode:UILineBreakModeWordWrap];
查看更多
爷的心禁止访问
3楼-- · 2019-01-08 14:26

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)))
查看更多
放我归山
4楼-- · 2019-01-08 14:28

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
查看更多
爷、活的狠高调
5楼-- · 2019-01-08 14:31

as for ios 7 and up this is the correct way:

NSString * buttonTitle = @"demo title";
CGSize stringSize = [buttonTitle sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:17.0f]}];
查看更多
登录 后发表回答