The UILabel is a great tool for displaying lines of text in any view and is easy to set up using the provided Interface Builder. Unfortunately, there is a deceptive option in the Label Attributes that says "Font Size: Adjust To Fit." This is a great feature because it means that the iPhone will automatically resize your text down in order to fit all of it into the label. Unfortunately, this feature only works when your label's layout is set to single-line. If your text is multiline like ours was, it won't adjust the font size at all!
Well we did some brief searching around to locate a solution to this problem but ended up simply writing our own. We have the following situation:
- We have dynamic text, the exact quantity of which varies.
- We want to place that text in a fixed-width and fixed-height UILabel
- We don't want the text to get cutoff if it doesn't fit perfectly
In order to meet this challenge, we wrote some simple code to automatically resize the text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //Create a string with the text we want to display. self.ourText = @"This is your variable-length string. Assign it any way you want!"; /* This is where we define the ideal font that the Label wants to use. Use the font you want to use and the largest font size you want to use. */ UIFont *font = [UIFont fontWithName:@"Marker Felt" size:28]; int i; /* Time to calculate the needed font size. This for loop starts at the largest font size, and decreases by two point sizes (i=i-2) Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */ for(i = 28; i > 10; i=i-2) { // Set the new font size. font = [font fontWithSize:i]; // You can log the size you're trying: NSLog(@"Trying size: %u", i); /* This step is important: We make a constraint box using only the fixed WIDTH of the UILabel. The height will be checked later. */ CGSize constraintSize = CGSizeMake(260.0f, MAXFLOAT); // This step checks how tall the label would be with the desired font. CGSize labelSize = [self.ourText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; /* Here is where you use the height requirement! Set the value in the if statement to the height of your UILabel If the label fits into your required height, it will break the loop and use that font size. */ if(labelSize.height <= 180.0f) break; } // You can see what size the function is using by outputting: NSLog(@"Best size is: %u", i); // Set the UILabel's font to the newly adjusted font. msg.font = font; // Put the text into the UILabel outlet variable. msg.text = self.ourText; |
To use the above text, you need to make a "IBOutlet UILabel *msg;" which you assign as the UILabel's Reference Outlet from the interface builder.
And there you have it: easy automatic resizing of multi-line text to fit in your fixed-size UILabel for the iPhone using Objective-C!