Auto sizing UILabel when using Autolayout

10,009

Solution 1

Make an IBOutlet for your width and height constraints, and use sizeToFit to change their constant property, and call needsUpdateConstraints

Solution 2

Using a "greater than constraint" for the height of the UILabel and calling sizeToFit within viewDidLayoutSubviews did the trick for me

I did not need to call needsUpdateConstraints.

You also need to set the number of lines to 0 to allow an unlimited amount of lines or > 1 if you want a limit.

Also the property preferredMaxLayoutWidth needs to be set, which is automatically set to the views width by the interface builder.

Share:
10,009
James
Author by

James

Updated on June 24, 2022

Comments

  • James
    James almost 2 years

    I'm creating a xib using autolayout (NSLayoutConsraint). Is there a way to use sizeToFit or something similar to make a UILabel fit its contents?

    I've tried setting a constraint of "greater than or equal to x" and tried setting the height to be below this. However, it keeps overwriting the height property. sitToFit doesn't seem to work when you have NSLayoutConstraints.

    How can I get the label to size appropriately?