具有两个标签(一个多行标签,一个单行)的水平UIStackView

时间:2019-11-27 06:22:34

标签: ios swift uilabel uistackview

我有一个水平UIStackView,其中有两个UILabel。第一个UILabel是多行(两行),而另一条仅是一行。它们都具有默认的内容压缩和抵抗优先级。 我的问题是,即使标签之间存在间隙,但第一行文字中的“最佳”字样还是排在第二行。我注意到第一个标签的宽度不超过总宽度的一半。

我想要的是第二个标签应始终显示其自身,第一个标签应将其自身的大小显示为剩余空间。如果无法容纳一行,则应为两行。但是,如果第二个标签太短而第一个标签很长,但两个标签都适合,则第一个标签应超过宽度的一半。

PS 在这种情况下,我需要使用UIStackView,因为还有其他情况。我知道在UIView中放置两个标签可以解决问题。

UIStackView:
   - Distribution: Horizontal
   - Alignment: Center
   - Spacing: 0
   UILabel:
     - Number of line: 2
     - Line break: Word wrap
   UILabel:
     - Number of line: 1

Screenshot

视图层次结构:

enter image description here

所需结果:

enter image description here

OR

enter image description here

编辑:我计算第二个标签的宽度并给出宽度约束。我认为它解决了我的问题,我会测试一下。

        //Give specific width to second label to make first one calculate right number of lines.
    if let font = UIFont(name: "Metropolis-ExtraBold", size: 15) {
        let fontAttributes = [NSAttributedString.Key.font: font]
        let size = (secondLabelText as NSString).size(withAttributes: fontAttributes)
        secondLabel.widthAnchor.constraint(equalToConstant: size.width).isActive = true
    }

3 个答案:

答案 0 :(得分:1)

尝试简化...

忘记计算任何宽度...重要的是水平Content HuggingContent Compression Resistance

将左侧(蓝色)标签保留为默认值:

Content Hugging Priority
    Horizontal: 251

Content Compression Resistance Priority:
    Horizontal: 750

但是将右(橙色)标签设置为:

Content Hugging Priority
    Horizontal: 1000

Content Compression Resistance Priority:
    Horizontal: 1000

结果:

enter image description here

唯一的其他问题是,如果右侧标签中的文本超过了视图的整个宽度,但是您并未表示可能需要那么多文本。

答案 1 :(得分:0)

首先将多行标签嵌入视图中,然后将标签约束到该视图(顶部,前导,尾随,底部)。之后,将带有多行标签和单行标签的视图添加到stackView。

然后,您可以使用.fillProportionally分配UIStackView,并使用interval值指定两个标签之间的间隔。

还要确保在正确的数字标签上将“必填项(1000)”用作水平内容压缩优先级。

视图层次结构:

enter image description here

结果:

enter image description here

enter image description here

标签之间的间距:

enter image description here

答案 2 :(得分:0)

您应该为每个设置不同的水平耐内容压缩

Multiple values

在这种情况下,蓝色的(多行)应该比橙色的(单行)少。

辅助提示:多行:250,单行:750

橙色设置: Orange Settings

蓝色设置: OrangeSettings

请注意,我已将橙色的行数限制设置为0。您可以将其设置为任何您喜欢的。但是,如果您想使其自身大小达到任何高度,则较高的视图应该具有比<250>更高的抗垂直压缩性