views:

1240

answers:

2

I need to measure the pixel width of a string in objective C can anyone point me to a link that explains how to do this? I haven't found anything that explains this well.

+3  A: 

Take a look at the NSString Application Kit Additions Reference, specifically boundingRectWithSize:options:attributes:. The value returned by that routine should give you the width of your NSString.

fbrereto
The documentation is not very clear on how to actually use `boundingRectWithSize:options:attributes:`. It would be nice if you could add an example of how to actually use this method to measure a string with a particular font.
PeyloW
+4  A: 

On iPhone OS it is slightly different, instead look at the NSString UIKit Additions Reference. The idea is the same as in Cocoa for Mac OS X, but there are more methods.

For single lines of text use:

- (CGSize)sizeWithFont:(UIFont *)font 
              forWidth:(CGFloat)width 
         lineBreakMode:(UILineBreakMode)lineBreakMode

And for multiline texts use:

- (CGSize)sizeWithFont:(UIFont *)font 
     constrainedToSize:(CGSize)size 
         lineBreakMode:(UILineBreakMode)lineBreakMode

The use of a UILineBreakMode as argument for single lines of text can be confusing, but this is because the line break is also used to define how to truncate the text.

PeyloW