Autoshrinking Text in a Multiline UILabel using Interface Builder

The problem: I wanted to have a fairly tall, multiline UILabel with auto-layout constraints that would shrink its text to fit within its bounds (instead of using sizeToFit and having the label re-size to accommodate the text).

Things I tried: The first thing I did was head over to Stack Overflow and see if anyone else had the same problem. There were lots of posts from 2011, 12 and 13, but nothing super recent; in fact, most of them used methods that are now deprecated. Still, I examined their answers and tried the following:

  • Creating a helper function that returned the correct font size based on the text length, label size, and the desired minimum and maximum font sizes using suggestions from here
  • From that same thread (towards the bottom), I tried using an extension of UILabel to automatically adjust the font size to fit
  • Finally, I hit the official UILabel Class Reference (which I probably should have started with) and found some useful notes, such as this note under the method “adjustsFontSizeToFitWidth”:

In iOS 6 and earlier, this property is effective only when the numberOfLines property is set to 1.

This led me to wonder what had actually changed post-iOS 6, since everyone on Stack Overflow was still saying that you had to set the numberOfLines property to 1 in order for text shrinking to work, or come up with some convoluted work-around.

The solution: I started tinkering around in Interface Builder, turning various settings on and off to see if anything did the trick.

  • I set “Autoshrink” to “Minimum font size.”
  • I set the font to my largest desirable font size (20) and set Lines to 10, which was as many lines as would fit in the label at that font size.
  • Then, I flipped what turned out to be the magic switch. I changed “Line Breaks” from “Word Wrap” to “Truncate Tail.”

So there you have it, folks. If you want your text to shrink to the size of your multiline label, try setting a specific number of lines (instead of 0, for infinite lines), turn word wrapping off, and make sure Autoshrink is set to either minimum font size or minimum font scale.

One thought on “Autoshrinking Text in a Multiline UILabel using Interface Builder

Comments are closed.