Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize UIView height based on UILabel text in Swift

Tags:

ios

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!

like image 651
ardevd Avatar asked Feb 24 '16 07:02

ardevd


1 Answers

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.

like image 162
Andrea Avatar answered Sep 19 '22 00:09

Andrea