Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLayoutConstraint for a UILabel to "grow" extra lines

I have a UILabel and I would like to set it so that it has a fixed width and variable height dependant on its text rather than its superView.

i.e. if the text is "Hello World." then the label will be...

------------------------
|Hello World.          |
------------------------

and if the text is "This is some very long text that goes over several lines." Then the label will be...

------------------------
|This is some very long|
|text that goes over   |
|several lines.        |
------------------------

I have already set the fixed width using an NSLayoutConstraint and I have set numberOfLines to 0 but it just keep one line height and concatenates the text with an ellipsis.

I know that there is something called "contentResistance" or something but I'm not sure of the name or how to use it.

Is this possible to do?

like image 420
Fogmeister Avatar asked Mar 07 '13 16:03

Fogmeister


1 Answers

You need to set the preferredMaxLayoutWidth of the label, to your fixed width. I don't know why it can't figure this out for itself since you've constrained to a width, but there you go.

If having to set a fixed size feels wrong in an Autolayout world (which it should!) then you can set the value from the label's width after layout has occurred, in viewDidLayoutSubviews. Be careful not to get into an infinite loop of invalidating your layout in this case.

like image 186
jrturton Avatar answered Oct 04 '22 07:10

jrturton