James
James

Reputation: 6509

Auto sizing UILabel when using Autolayout

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?

Upvotes: 7

Views: 10041

Answers (3)

HeikoG
HeikoG

Reputation: 1001

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.

Upvotes: 1

PatrickNLT
PatrickNLT

Reputation: 4425

You should try to lower your height constraint priority.

Upvotes: 0

borrrden
borrrden

Reputation: 33423

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

Upvotes: 4

Related Questions