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.
My approach to compute the dynamic height of UILabel.
Wrap to function:
Finally, it worked. Thank you guys.
I was not getting it to work because i was trying to resize the label in
heightForRowAtIndexPath
method:and (yeah silly me), i was resizing the label to default in
cellForRowAtIndexPath
method - i was overlooking the code i had written earlier:You may use it as a method, as well. @Pyjamasam is very much true so i am just making its method. It may be helpfull for some one else
and just set it like this
UILabel extension based on this answer for Swift 4 and above
Can be used like:
Swift 2:
The interesting lines are
sizeToFit()
in conjunction with setting aframe.size.height
to the max float, this will give room for long text, butsizeToFit()
will force it to only use the necessary, but ALWAYS call it after setting the.frame.size.height
.I recommend setting a
.backgroundColor
for debug purposes, this way you can see the frame being rendered for each case.Since sizeWithFont is deprecated I use this one instead.
this one get label specific attributes.