I have an NSString and want to fit it into a rectangle. The rectangle has a specified size, lets say width=150 and height=30. When the String is short and has only one character, it can be as high as the rectangle. More specific: It can have a big font size. But if the string has too much characters and would exceed the bounds of the rectangle, it must become smaller. More specific: It's font size must become smaller, so that it won't exceed the bounds of the rectangle. Is there a way of doing that without messing around in core graphics?
For some reason, UILabel's adjustsFontSizeToFitWidth Property has no effect. The text keeps beeing small even if there is plently of space.
I've set that to
label.adjustsFontSizeToFitWidth = YES;
but nothing happens. I hope there is another way to do that…
Best Answer
There are several part to
UILabel
that make this possible, but first you have to know if you want to truncate the string or make the font size smaller to fit in the rectangle.For both cases you'll want to set the
UILabel
'snumberOfLines
property to0
, allowing the label to wrap as much as necessary. Then you'll want to set theframe
of theUILabel
to match the rectangle you're looking to fit. From there you take one of two paths:lineBreakMode
property toUILineBreakModeClip
,UILineBreakModeHeadTruncation
,UILineBreakModeTailTruncation
, orUILineBreakModeMiddleTruncation
depending on the truncation behavior you're looking for.lineBreakMode
to eitherUILineBreakModeWordWrap
or `UILineBreakModeCharacterWrap' depending on your preference. Then you'll need to enter a loop to figure out the right font size. Start with a reasonable font size (e.g., 12) and:font
property of theUILabel
with aUIFont
that matches that size- (void) sizeToFit
for theUILabel
.frame
for theUILabel
:For the latter option you'll want to make sure you're not squeezing the text into oblivion, so you'll want to put a minimum size cap on the font size.
You can get more information from the UILabel and UIFont documentation.