Auto sizing UILabel when using Autolayout

吃可爱长大的小学妹 提交于 2019-12-21 12:21:49

问题


I'm creating a xib using autolayout (NSLayoutConsraint). Is there a way to use sizeToFit or something similar to make a UILabel fit its contents?

I've tried setting a constraint of "greater than or equal to x" and tried setting the height to be below this. However, it keeps overwriting the height property. sitToFit doesn't seem to work when you have NSLayoutConstraints.

How can I get the label to size appropriately?


回答1:


Make an IBOutlet for your width and height constraints, and use sizeToFit to change their constant property, and call needsUpdateConstraints




回答2:


Using a "greater than constraint" for the height of the UILabel and calling sizeToFit within viewDidLayoutSubviews did the trick for me

I did not need to call needsUpdateConstraints.

You also need to set the number of lines to 0 to allow an unlimited amount of lines or > 1 if you want a limit.

Also the property preferredMaxLayoutWidth needs to be set, which is automatically set to the views width by the interface builder.




回答3:


You should try to lower your height constraint priority.



来源:https://stackoverflow.com/questions/13105544/auto-sizing-uilabel-when-using-autolayout

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