Iphone – How to calculate the size of a UIFont when text in label is constrained down to fit width

cocoa-touchiphoneuikit

Imagine a UILabel, which is 200 pixels wide and 50 pixels high. The label has text inside, and the label makes the text smaller so that it fits into the label. But now, how would you get the size of that UIFont how it is visible in the label? Lets imagine the font size was given with huge 100, and the label squeezes it down to 15. And then, you want to make some other labels with little text, which has same font size. Is there a way to obtain the UIFont's font size after getting squeezed by the label?

Best Answer

If you pass the size of the UILabel and the breakMode, etc. to:

CGSize  size = [label.text sizeWithFont:label.font minFontSize:10 actualFontSize:&actualFontSize forWidth:200 lineBreakMode:UILineBreakModeTailTruncation];

actualFontSize should be what you are looking for.

UPDATE:

The above has been deprecated. The method to use now is:

- (CGRect)textRectForBounds:(CGRect)bounds
     limitedToNumberOfLines:(NSInteger)numberOfLines

Here's an example

CGSize  size = [label textRectForBounds:label.bounds
     limitedToNumberOfLines:1].size;