David David - 17 days ago 5
Objective-C Question

How to get the width of an NSString?

I am trying to get the width of an NSString (ex. NSString *myString = @"hello"). Is there a way to do this?

Thanks.

Answer

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;
 }
Comments