IOS/Autolayout: Make UILabel go to more than one line with Autolayout

…衆ロ難τιáo~ 提交于 2020-01-16 10:37:06

问题


I need to get a UILabel to go to more than one line if text requires with autolayout. In code and also in storyboard for good measure I have set numberOfLines to 0 and wordwrapping on and I've also called sizeToFit.

The full amount of text will display on multiple lines if I set the height constraint for the label to a large enough value such = 200. But with short text, it does not contract, leaving a lot of white space. But if I set the height constraint to a lower value such as >=21 then it shows only one line and cuts off everything else.

The view hierarchy is View-Scrollview-Contentview-elements I set a bottom constant for the lowest element with a priority of 250 so it should adjust. Autolayout shows no errors

Nothing, however, short of creating a huge height constraint for the label lets the label extend to multiple lines.

Would appreciate any suggestions on how to solve this issue.

In viewwillappear:

_myLabel.lineBreakMode = UILineBreakModeWordWrap;//deprecated but I threw it in too
_myLabel.lineBreakMode = NSLineBreakByWordWrapping;
_myLabel.numberOfLines = 0;
[_myLabel sizeToFit];

// height constraint for label

height>=21//text does not extend more than one line
height=200//text does extend more than one line but leaves lots of whitespace if text is short ie it does not shrink.

回答1:


from Storyboard ,

  • Set property

    _myLabel.numberOfLines = 0;
    
  • Set constraint

    _myLabel.height <= 200
    

Note : label height will automatically set according to its text content. From constraint relationship label height is atmost 200 and atleast height is its text content (automatically adjustable).

Now still any doubt then ask.




回答2:


Calling sizeToFit with Autolayout will not have any effect.

You should set the Vertical Content Compression Resistance Priority of the label to required. This priority forbids Autolayout to give the label a smaller height as needed to display all lines:

[_myLabel setContentCompressionResistancePriority:1000 
     forAxis:UILayoutConstraintAxisVertical];

You may apply this priority in size inspector of interface builder as well.




回答3:


You should add 2 constraint regarding the height of the label:

  1. Constraint height <= 200 priority 1000
  2. Constraint height >= 21 priority 1000



回答4:


Give proper leading, trailing, top, bottom constraints to your label and in storyboard set numberOfLines = 2. The reason why i specified constraints is that auto-layout will then automatically resize the intrinsic size of the label based on the content. Hope, this was helpful.



来源:https://stackoverflow.com/questions/49428347/ios-autolayout-make-uilabel-go-to-more-than-one-line-with-autolayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!