iOS 如何使用自动布局根据文本长度更改 UILabel 宽度

How to change UILabel width based on text length in iOS Using Auto-Layouts

我想显示两个 UILabel,但是 UILabel 的文本长度可变,根据文本大小 UIlabel 的宽度需要使用自动布局来增加。

为此,我在下面写了两个 UIlabel

的自动布局

第一个标签:

1)leading Space 
2)Top space
3)Width
4)height
5)Horizontal spacing

第二个标签:

1)Trailing space
2)Top space
3)Width
4)height

我们该怎么做?

请帮帮我。

我的代码:

textLabel1.numberOfLines = 0
        textLabel1 .sizeToFit()
        textLabel1.text = "asdfdsfdghjgjhkhkjlhjkhjk"

textLabel2.numberOfLines = 0
        textLabel2 .sizeToFit()
        textLabel2.text = "asdfdsfdghjgjhkhkjlhjkhjk"

首先,您需要将 UILabel 的 属性 numberOfLines 设置为零,并将文本换行设置为自动换行。然后给出所需的约束。

如果你没有得到想要的结果,那么你需要通过boundingRectWithSize:...方法计算标签的动态高度,并相应地给出高度约束。

Select第一个UILabel,设置Leading,Top,bottom并设置固定宽度,然后去size Inspector -> select 固定宽度约束 -> 关系 -> select 大于等于,例子下面给出,

select第二个UILabel,设置Leading,Bottom,fixed width,然后执行以上相同的过程,

希望对您有所帮助