David David - 1 year ago 115
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?


Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download