简体   繁体   English

多线UILabel的宽度与内在大小UILabel的宽度相同

[英]Multiline UILabel same width as intrinsic content sized UILabel

I'm trying to align two UILabel's using Auto Layout, where the first label has no set width but using intrinsic content size and the second should be the same width as the first, wrapping text to new lines. 我正在尝试使用自动布局对齐两个UILabel,其中第一个标签没有设置宽度但使用内在内容大小,第二个标签应该与第一个相同,将文本包装到新行。

Ideally the second label should have number lines set to 0 to work with Dynamic Type, but I've set it to 2 for the time being and even given it a specific height. 理想情况下,第二个标签应该将数字行设置为0以使用动态类型,但我暂时将其设置为2 ,甚至给它一个特定的高度。 Yet when I try to align either equal widths or trailing , the intrinsic content size label expands to the width of the multiline label as if it was all on one line (see below illustration). 然而,当我尝试对齐equal widthstrailing随时,内在内容大小标签会扩展到多行标签的宽度,就像它在一条线上一样(见下图)。

What I'm after: 我在追求的是什么: 我之后的效果

What I'm seeing: 我所看到的: 我得到的效果

Is there any way for me to achieve what I want without specifying a width for the first label? 有没有办法让我达到我想要的而不指定第一个标签的宽度? I'd like it to expand with the content to account for dynamic type, and for the second label to have the same width and wrap all text to a new line. 我希望它扩展内容以考虑动态类型,并使第二个标签具有相同的宽度并将所有文本包装到新行。

You can do it without hooking anything to the code. 你可以在不挂钩代码的情况下完成。 The key point of this solution is the content hugging priority for the label which size will be calculated based entirely on the intrinsic content size. 此解决方案的关键点是标签的内容拥抱优先级 ,其大小将完全基于内在内容大小计算。

Intrinsic content size label 内在内容大小标签

  • Set the horizontal content hugging priority to required (1000) 将水平内容拥抱优先级设置为必需(1000)

Multiline label (lorem ipsum label) 多行标签(lorem ipsum标签)

  • Align leading to Intrinsic content size label 对齐导致内在内容大小标签
  • Align trailing to Intrinsic content size label 将尾随对齐到内在内容大小标签


Xcode configurations for both labels (left: Intrinsic, right: Multilabel) 两个标签的Xcode配置(左:内在,右:多标签)

内在内容大小标签的配置 多行标签的配置

layoutSubviews中 ,将第二个标签的preferredMaxLayoutWidth设置为第一个标签内部宽度,类似于:

secondLabel.preferredmaxlayoutwidth = firstLabel.intrinsicContentSize.width

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM