17

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Mike2012
  • 7,629
  • 15
  • 84
  • 135
  • 5
    You should not ask for a generic objective-c answer when this question is really about features in Cocoa for Mac OS X or Cocoa Touch for iPhone OS. Objective-C is just the programming language, that both Cocoa and Cocoa Touch uses. – PeyloW Sep 17 '09 at 10:17
  • 4
    Is there any other use of objective-c besides programming for Mac OS or IOS? If so, is it significant? – user4951 Nov 21 '12 at 09:42

3 Answers3

27

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
  • 36,742
  • 12
  • 80
  • 99
  • This seems to work fine for usual fonts but it doesn't seem to give the exact bounds for fonts such as Zapfino. Sample code is at http://paste.lisp.org/display/130803 and output screenshot is at http://ScrnSht.com/juixwk. Any idea why and how to solve it? – trss Aug 01 '12 at 11:54
  • deprecated in iOS7.. the docs don't refer to any replacement.. is there any? – abbood Aug 12 '13 at 14:44
  • The current iOS7 docs (Xcode 5.0.1) do refer to replacements (which tend to be iOS7-only). – JLundell Nov 01 '13 at 14:06
  • lineBreakMode options now start with NS. e.g. NSLineBreakByWordWrapping – bret Mar 06 '14 at 19:15
5

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
  • 35,429
  • 19
  • 126
  • 178
  • 8
    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 Sep 17 '09 at 10:19
0

The above solution is now deprecated. Check this for iOS 7+

 sizeWithFont:constrainedToSize:lineBreakMode 

is deprecated now. Use below code snippet,

UIFont *font=[UIFont fontWithName:@"Arial" size:16.f];

NSString *name = @"APPLE";

CGSize size = [name sizeWithAttributes:@{NSFontAttributeName:font}];
Gobi M
  • 3,243
  • 5
  • 32
  • 47