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…
There are several part to
UILabelthat 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‘snumberOfLinesproperty to0, allowing the label to wrap as much as necessary. Then you’ll want to set theframeof theUILabelto match the rectangle you’re looking to fit. From there you take one of two paths:lineBreakModeproperty toUILineBreakModeClip,UILineBreakModeHeadTruncation,UILineBreakModeTailTruncation, orUILineBreakModeMiddleTruncationdepending on the truncation behavior you’re looking for.lineBreakModeto eitherUILineBreakModeWordWrapor `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:fontproperty of theUILabelwith aUIFontthat matches that size- (void) sizeToFitfor theUILabel.framefor 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.