Resize UIView based on UILabel text in Swift

So, I have a simple one UIViewwith the UILabelinside. Height is currently UIViewtough, UIViewwhich is a problem when the text is UILabelso long that the content needs more height than it provides UIView.

Is there a simple method to calculate the appropriate height for UIViewto show all the contents contained UILabel?

Thank!

+5
source share
1 answer

If you use automatic layout:
you just need to bind the leading, trailing, upper, and lower parts of your UILabel to its super-root (leading, trailing, upper, and lower).
Set the property numberOfLinesto 0, which means how much you need. Now you can limit the width of your UIlabel instance to a specific number or set it preferredMaxLayoutWidth, basically you say you want your shortcut to create another line if the text is larger than that width.
Now comes the magic of the layout, each view has a property intrinsicContentSizethat does not UILabelcorrespond to the size occupied by the text. This forces one to UILabel“push” its surveillance boundaries to adapt to its content size.
Of course, the supervisor should not have any height restrictions.

:
  - (CGSize)sizeThatFits:(CGSize)size, CGFLOAT_MAX , , , , .

+13

All Articles