David David - 4 months ago 51
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?



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;