Objective-c – How to fit a String into a rectangle

cocoa-touchiphoneobjective cuikit

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's numberOfLines property to 0, allowing the label to wrap as much as necessary. Then you'll want to set the frame of the UILabel to match the rectangle you're looking to fit. From there you take one of two paths:

  • Truncation: Set the lineBreakMode property to UILineBreakModeClip, UILineBreakModeHeadTruncation, UILineBreakModeTailTruncation, or UILineBreakModeMiddleTruncation depending on the truncation behavior you're looking for.
  • Resizing: Set the lineBreakMode to either UILineBreakModeWordWrap 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:
    • Set the font property of the UILabel with a UIFont that matches that size
    • Call - (void) sizeToFit for the UILabel.
    • Check the frame for the UILabel:
      • If the frame will fit within the bounds you need it to, you're done
      • If the frame is still to big, drop the size of the font and repeat the loop

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.