Hi. I have a UILabel of a fixed size. This size cannot be changed, as the interface is all set up to have that label there at that particular size.
I'm trying to get the largest font size for any font I might put in that label, that will fit all of the text inside that label.
The label can have up to four lines, with the text contents being centred horizontally and vertically.
I've seen a bunch of suggestions about using boundingRectWithSize:options:attributes:context but that always returns the maxium I put in, i.e. 50. Here's a snippet of my code:
theLabel.frame = labelRect;
theLabel.lineBreakMode = NSLineBreakByWordWrapping;
// Start at the largest size
CGFloat fontSize = 50.0;
CGSize constraintSize = CGSizeMake(theLabel.frame.size.width, theLabel.frame.size.height); // This is the size of my UILabel
NSStringDrawingContext *context = [NSStringDrawingContext new];
context.minimumScaleFactor = 0.5;
do {
// Set the font to the current size
theLabel.font = [UIFont fontWithName:theLabel.font.fontName size:fontSize];
// Find label size for current font size
CGRect textRect = [[theLabel text] boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
attributes:@{NSFontAttributeName:theLabel.font}
context:context];
CGSize labelSize = textRect.size;
NSLog(@"labelSize.height = %.2f, theLabel.frame.size.height = %.2f", labelSize.height, theLabel.frame.size.height);
// Done, if created label is within target size
if(ceilf(labelSize.height) <= ceilf(theLabel.frame.size.height))
break;
// Otherwise, redice the font size and try again
fontSize -= 1.0;
} while(fontSize > 5.0); // Minimum size = 5.0
NSLog(@"new font size = %.2f", fontSize);
[theLabel setFont:[UIFont fontWithName:theLabel.font.fontName size:fontSize]];
The output is this:
labelSize.height = 0.00, theLabel.frame.size.height = 149.00
new font size = 50.00
What am I doing wrong? Why does labelSize.height always equal zero?