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:05

Send the string a sizeWithAttributes: message, passing a dictionary containing the attributes with which you want to measure the string.

查看更多
Melony?
3楼-- · 2019-01-08 14:07

Sorry my question was not detailed enough and is not exactly what I'm trying to do. I am using a text storage, layout manager and a text container. The solution is to use the layout manager to determine the rectangle that bounds the rect. Here is the code.

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:@"hello"];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc] init];

[layoutManager addTextContainer:textContainer];
[textContainer release];

[textStorage addLayoutManager:layoutManager];
[layoutManager release];

//Figure out the bounding rectangle
NSRect stringRect = [layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer];
查看更多
Luminary・发光体
4楼-- · 2019-01-08 14:10

Using the UILabel's attributed string:

- (CGSize)getStringSizeWithText:(NSString *)string font:(UIFont *)font{

    UILabel *label = [[UILabel alloc] init];
    label.text = string;
    label.font = font;

    return label.attributedText.size;
}
查看更多
\"骚年 ilove
5楼-- · 2019-01-08 14:17

Just in case you are wondering how to check a label size, you should use the UIFont, instead of the NSFont (not even sure if exists)

查看更多
一夜七次
6楼-- · 2019-01-08 14:21
UIFont * font = [UIFont systemFontOfSize:15];

CGSize stringSize = [aString sizeWithFont:font]; 

CGFloat width = stringSize.width;
查看更多
女痞
7楼-- · 2019-01-08 14:24

Here's a relatively simple approach. Just create an NSAttributedString with the appropriate font and ask for its size:

- (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
     NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
     return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
 }
查看更多
登录 后发表回答