Iphone – How to figure out the font size of a UILabel when -adjustsFontSizeToFitWidth is set to YES

cocoa-touchiphoneuikituilabel

When myLabel.adjustsFontSizeToFitWidth = YES, UILabel will adjust the font size automatically in case the text is too long for the label. For example, if my label is just 100px wide, and my text is too long to fit with the current font size, it will shrink down the font size until the text fits into the label.

I need to get the actual displayed font size from UILabel when the font size got shrunk down. For example, let's say my font size was actually 20, but UILabel had to shrink it down to 10. When I ask UILabel for the font and the font size, I get my old font size (20), but not the one that's displayed (10).

Best Answer

I'm not sure if this is entirely accurate, but it should be pretty close, hopefully. It may not take truncated strings into account, or the height of the label, but that's something you might be able to do manually.

The method

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

will return the text size, and notice that it also has a reference parameter for the actual font size used.