iOS AutoLayout multi-line UILabel

There’s an answer this question on objc.io in the “Intrinsic Content Size of Multi-Line Text” section of Advanced Auto Layout Toolbox. Here’s the relevant info:

The intrinsic content size of UILabel and NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.

Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.

The code they give for use inside a view controller:

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [self.view layoutIfNeeded];
}

Take a look at their post, there’s more information about why it’s necessary to do the layout twice.

Leave a Comment