Swift-如何根据UIView的大小调整UIView的大小(在内部) [英] Swift - How to resize a UIView based on its UILabel size (that is inside)
问题描述
我在Swift中有些新知识,对此我需要一些帮助:
I'm a bit new in Swift, and I need some help with this:
我在UIView中有一个UILabel,此标签可以接收任意数量的文本.因此,我想根据接收到的文本来调整UILabel的大小,并且还要调整其容器UIView的大小.UILabel必须具有最大宽度,但不能具有最大高度.这与Whatsapp中带有消息文本的情况非常相似(他的绿色容器内部的文本也随之增长).
I have a UILabel inside a UIView, and this label can receive any ammount of text. So I want to resize the UILabel based on the text it receives, and also resizes its container, the UIView. The UILabel must have a max width but not max height. It is very similar to what happens in Whatsapp with a message text (his green container grows accordly the text inside).
我相信这与自动布局有关,但我真的不了解其中的大部分内容.
I believe it is about auto layout, but I really can't understand most of it.
动态创建.
有人可以帮助我吗?
推荐答案
包含Label的UIView不应具有固定的高度.只需添加约束以设置UIView宽度和X/Y坐标即可.
The UIView that contains the Label should not have a fixed height then. Just add constraints to set the UIView width and the X/Y coordinates.
在其中,UILabel应该将固定的约束固定为UIView的顶部/底部和右/左,并将其numberOfLines设置为0
Inside it the UILabel should have fixed constraints to Top/Bottom and Right/Left to the UIView and also set it's numberOfLines to 0
在这些约束下,容器视图将展开以根据文本调整高度.
With these constraints the container View will expand to adjust the height based on the text.
请参阅所附的屏幕截图
添加容器视图约束(注意,未添加底部或高度约束)
添加标签约束(所有UIView Edge的固定约束)
带有短文本的结果
带有长文本的结果
这篇关于Swift-如何根据UIView的大小调整UIView的大小(在内部)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!