Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring the pixel width of a string

I need to measure the pixel width of a string in Cocoa Touch. Can anyone point me to a link that explains how to do this?

like image 342
Mike2012 Avatar asked Sep 16 '09 21:09

Mike2012


1 Answers

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.

like image 94
PeyloW Avatar answered Nov 07 '22 18:11

PeyloW