Consider I have the following text in a UILabel
(a long line of dynamic text):
Since the alien army vastly outnumbers the team, players must use the post-apocalyptic world to their advantage, such as seeking cover behind dumpsters, pillars, cars, rubble, and other objects.
I want to resize the UILabel's
height so that the text can fit in. I'm using following properties of UILabel
to make the text within to wrap.
myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;
Please let me know if I'm not heading in the right direction. Thanks.
In iOS 6 Apple has added a property to UILabel that greatly simplifies dynamic vertical resizing of labels: preferredMaxLayoutWidth.
Using this property in combination with lineBreakMode = NSLineBreakByWordWrapping and sizeToFit method allows easily resize a UILabel instance to the height that accommodates the entire text.
A quote from iOS documentation:
A sample:
To do this in Swift3 following is the code:
My code:
Check this work perfectly without adding Single line of code. (Using Autolayout)
I made a demo for you according to your requirement. Download it from below link,
Autoresize UIView and UILabel
Step by Step Guide :-
Step 1 :- Set constrain to UIView
1) Leading 2) Top 3) Trailing (From mainview)
Step 2 :- Set constrain to Label 1
1) Leading 2) Top 3) Trailing (From it's superview)
Step 3 :- Set constrain to Label 2
1) Leading 2) Trailing (From it's superview)
Step 4 :- Most tricky give botton to UILabel from UIView .
Step 5 :- (Optional) Set constrain to UIButton
1) Leading 2) Bottom 3) Trailing 4) Fixed Height (From mainview)
Output :-
Note :- Make sure you have set Number of lines =0 in Label property.
I hope this info enough to understand Autoresize UIView according to UILabel's height and Autoresize UILabel According to text.
Here is a category version:
UILabel+AutoSize.h #import
UILabel+AutoSize.m
Please set constraints for UILable in storyboard including top left bottom right