ios AutoLayout 动态调整 UILabel 高度和宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36554130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:53:37  来源:igfitidea点击:

AutoLayout to dynamically size UILabel Height and Width

iosswiftautolayout

提问by niks290192

I have one UILabel and One UIView contains other subviews side by side in Storyboard. The UIView should butt up against the right edge of the UILabel(trailing constraint of 1), but I also need the UIlabel (the one on the left) to set it's width equal to it's content size unless it hits a max width. Visually:

我有一个 UILabel,一个 UIView 在 Storyboard 中并排包含其他子视图。UIView 应该靠在 UILabel 的右边缘(尾随约束为 1),但我还需要 UIlabel(左侧的)将其宽度设置为等于其内容大小,除非它达到最大宽度。视觉上:

|Label text| |UIViewWithSubviews|

|标签文本| |UIViewWithSubviews|

And I need the following constraints:

我需要以下约束:

1) Label should resize width wise unless it hits a max size and height is also dynamic that means when text reaches the maximum width then the word wrap will break the sentence to another line. and UIview will become vertical to UIlabel.

1)标签应该调整宽度,除非它达到最大尺寸并且高度也是动态的,这意味着当文本达到最大宽度时,自动换行会将句子分成另一行。并且 UIview 将垂直于 UIlabel。

2) UIView should always be butted up against the right edge of label one in vertical center.

2) UIView 应始终靠在垂直中心的标签一的右边缘。

How do I set this up in Storyboard?

如何在 Storyboard 中进行设置?

Thanks In advance.

提前致谢。

回答by Tien

Is this what you need?

这是你需要的吗?

enter image description here

在此处输入图片说明

Here is how i did in Interface Builder.

这是我在 Interface Builder 中所做的。

enter image description here

在此处输入图片说明

回答by Daniel Hall

1) Set a width constraint on the UILabel that is "Less Than Or Equal" to the max width you want.

1) 在 UILabel 上设置宽度约束,即“小于或等于”到您想要的最大宽度。

2) Set the number of lines for the UILabel in the storyboard to be 0. This enables the wrapping you are looking for. Don't set any height constraint at all.

2) 将故事板中 UILabel 的行数设置为 0。这将启用您正在寻找的包装。根本不要设置任何高度限制。

3) Set up constraint to center the UIView vertically with the UILabel.

3) 设置约束以将 UIView 与 UILabel 垂直居中。

4) Your other existing constraints sound fine. Just make sure that the UILabel has a clear x and y position, for example by anchoring to the leading and top edges of the superview. And make sure the UIView similarly has sufficient constraints as needed in addition to the vertical centering and the leading edge alignment with the UILabel.

4)您的其他现有约束听起来不错。只需确保 UILabel 具有清晰的 x 和 y 位置,例如通过锚定到超级视图的前缘和上缘。并确保 UIView 除了垂直居中和与 UILabel 的前缘对齐之外,还根据需要具有足够的约束。