views:

462

answers:

2

I have a UILabel that displays some chars. Like "x", "y" or "rpm". How can I calculate the width of the text in the label (it does not ues the whole available space)? This is for automatic layouting, where another view will have a bigger frame rectangle if that UILabel has a smaller text inside. Are there methods to calculate that width of the text when a UIFont and font size is specified? There's also no line-break and just one single line.

+2  A: 

What you want is in UIStringDrawing.h

CGFloat actualFontSize = 12.0;
CGSize sizeNeeded = [plainText sizeWithFont:[UIFont systemFontOfSize:12.0] minFontSize:12.0 
   actualFontSize:&actualFontSize forWidth:widthOfMyLabel lineBreakMode:UILineBreakModeTailTruncation];
Glenn Howes
+1  A: 

You can do exactly that via the various sizeWithFont: methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):

NSString* someString = @"Hello World";
NSFont* yourFont = // [UIFont ...]
CGSize stringBoundingBox = [someString sizeWithFont:yourFont];

There are several variations of this method, eg. some consider line break modes or maximum sizes.

Daniel Rinser