使用自动布局以编程方式调整标签宽度

Programmatically adjust label width with auto layout

我在视图中有两个标签,其中一个标签可以通过用户输入(添加数字)进行更改。约束以编程方式设置,视觉格式语言的水平约束如下所示:

"H:|-11-[label1]-[label2(>=30@750)]-10-|"

结果如下:

|[the text in label1...][label2]|

但是当用户将一些数字添加到标签 2 时,它看起来像:

|[the text in label1...][......]|

我试过使用 updateConstraintsIfNeeded()updateConstraints()layoutIfNeeded(),但没有任何效果。

这是我在输入额外数字后尝试得到的结果:

|[the text in...][extra numbers]|

我做错了什么?一切都以编程方式编码。

尝试这样做:

"H:|-11-[label1(<=70@750)]-[label2]-10-|"

您在第一个标签中设置了低优先级,因为标签 2 是您要缩放以适合文本的标签

这是我结果的两张图片

Before clicking in the Add button

After clicking in the Add button