Take a look at [NSString boundingRectWithSize:options:attributes:context:]
You can pass MAXFLOAT
for both height and width of the parameter size to get the actual size of the text.
EDIT: here's some code that calculates the ideal font size fairly efficiently, using the non-deprecated method:
+(float) calulateHeightFromMaxWidth:(NSString*)text withMaxWidth:(float)maxWidth withMaxFontSize:(float)maxFontSize{
// The less exact you try to match the width, the fewer times the method will need to be called
CGFloat textWidthMatchDelta = 10;
CGFloat fontSize = maxFontSize;
CGFloat minFontSize = 0;
// If drawing a single line of text, omit `|NSStringDrawingUsesLineFragmentOrigin`.
NSUInteger textOptions = NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin;
while (YES) {
CGRect textRect = [text boundingRectWithSize:CGSizeMake(maxWidth, MAXFLOAT)
options:textOptions
attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:fontSize]
context:nil];
CGFloat textWidth = CGRectGetWidth(textRect);
if (textWidth > maxWidth) {
maxFontSize = fontSize;
fontSize /= 2.0f;
} else if (textWidth + textWidthMatchDelta < maxWidth) {
minFontSize = fontSize;
fontSize = minFontSize + (maxFontSize - minFontSize) / 2.0f;
} else {
break;
}
}
return fontSize;
}