I have a UILabel in which the text is automatically shrunk to fit. Once this has happened, I need to know the point size of the resulting font so that I can set that exact same size in another label elsewhere.
If I access label.font.pointSize I get back the original size, not the shrunk size. So I then tried using this NSString addition to calculate the font size:
- (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode
However, that doesn’t work for me either because if doesn’t take into account the label’s height constraint, only its width. (In my case the font needs shrinking further to fit in the frame’s height).
This seems to leave me with just one absolutely horrible option, and that’s to call the following function repeatedly until I’ve found the maximum height that will actually fit into the frame:
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
Clearly that would be both very inefficient and nasty.
Does anyone have a better solution?
Tim
Well, in the advent that no-one can provide me with a better option, I thought I’d share a category that I’ve written to solve the problem the hard way.
However, if there’s a direct way to access the shrunk font size of a UILabel that’d obviously be ideal…
Without further ado, this function will return an auto-shrunk font size that fits within the constrained size.
Interface:
Implementation: