views:

83

answers:

5

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

Thanks.

A: 

By "width" do you mean the number of characters in the string?

NSUInteger len = [myString length];

NSString docs

jtbandes
No. I mean the width of the bounding rectangle.
David
A: 

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];
David
That's the long way. If you normally have a text storage, layout manager, and text container anyway (and having a text view counts), then that's fine, but there are a couple of much shorter ways.
Peter Hosey
+2  A: 

Hi David -

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;
 }
Stephen Poletto
That leaks the attributed string.
Peter Hosey
True - I've assumed a garbage collected environment.
Stephen Poletto
+1  A: 

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

Peter Hosey
A: 

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

CGSize titleSize = [title sizeWithFont:titleFont 
                     constrainedToSize:contentCellSize 
                         lineBreakMode:UILineBreakModeWordWrap];
Mullzk