ardevd
ardevd

Reputation: 3407

Resize UIView height based on UILabel text in Swift

So I have a simple UIView with a UILabel contained within. Currently, the height of the UIView is hardcoded which is an issue when the UILabel text is so long enough for the content to require more height than the UIView provides.

Is there a simple method to calculate the appropriate height for the UIView in order to show all the content in the contained UILabel?

Thank you!

Upvotes: 7

Views: 8105

Answers (1)

Andrea
Andrea

Reputation: 26385

If you are using auto layout:
You just need to pin leading, trailing, top and bottom of your UILabel to its superview (leading, trailing, top and bottom).
Set the numberOfLines property to 0, that means how many you need. Now you can decide to constraint the width of your UIlabel instance to a specific number or set the preferredMaxLayoutWidth, basically you are saying that you want your label to create another line if the text is bigger than this width.
Now it comes the magic of layout, each view has an intrinsicContentSize property, on UILabel it correspond to the size occupied by the text. This makes the UILabel "push" its superview bounds to adapt to its content size.
Of course the superview must not have any constraints in height.

If you are not using auto layout:
After setting the text you can send the label the - (CGSize)sizeThatFits:(CGSize)size method by setting a fixed width and CGFLOAT_MAX in height, it will return the size occupied by the full text thus you cab set the superview frame accordingly.

Upvotes: 14

Related Questions