Your guess is right on – it has to do with Auto Layout. When the system needs to lay out a multiline label, it needs to know two dimensions: the width and the height of the label.
Sometimes, you constrain one or both explicitly: you can say "I want my label to be 300 points wide," or "I want my label exactly one line tall." The system can then figure out the other dimension based on your constraint and the text in the label.
Other times, though, you don't constrain either – you might want the label to wrap within available space, but shrink horizontally if it doesn't have a lot of text in it, so you don't constrain either the width or the height exactly. In that case, Auto Layout can get confused, because text doesn't really have an "intrinsic size" the way a lot of other content does. For example:
A sentence can be quite long horizontally,
or
it
might
be
skinny
but
tall
Both of those layouts – and many in between – would be equally valid in Auto Layout's eyes. To help guide it, Apple introduced the preferredMaxLayoutWidth
property for wrapping labels. If your label doesn't explicitly set an exact width or height, UIKit will start laying out text on the first line until you hit the preferred maximum width for that layout, then wrap and continue the process on each subsequent line.
If preferredMaxLayoutWidth
isn't set, the text won't extend beyond the bounds
of the label. Instead, one of two things would happen:
- The label would get wider and wider, expanding its
frame.size.width
to fit the text on one line until it was all rendered, or
- The label would truncate its text
Effectively, this makes the preferredMaxLayoutWidth
property a mechanism for guiding Auto Layout's behavior when wrapping text without requiring you to write a bunch of dynamic constraints code to achieve the same effect. It's quite a handy shortcut, especially when combined with some of the Interface Builder options to set the max layout width to e.g. the First Runtime Layout Width
or Automatic
.
Hope that helps clear things up!