本文介绍了带有两个标签(一个多行标签,一个单行)的水平UIStackView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a horizontal UIStackView which has two UILabel in it. First UILabel is multiline (two line) and other one is one line only. They both have default content compression and resistance priorities. My problem is that even there is a gap between labels, "best" word in first text goes second line. I noticed that first label doesn't goes beyond half of total width.

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

What I want is that second label should always show itself and first label should size It self for remaining space. If It can't fit to one line It should be two line. However, If second label is too short and first label is a long one but both of them can fit, first label should go beyond half of the width.

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

P.S I need to use UIStackView in this scenario because there are other cases. I know putting two label inside UIView may solve the problem.

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

视图层次结构:

所需结果:

OR

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

I calculate the width of second label and give width constraint. I think It solved my problem, I'll test a bit.

        //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
    }

推荐答案

尝试简化...

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

Forget calculating any widths... what matters is the horizontal Content Hugging and Content Compression Resistance

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

Leave the left (blue) label at the defaults:

Content Hugging Priority
    Horizontal: 251

Content Compression Resistance Priority:
    Horizontal: 750

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

But set the right (orange) label to:

Content Hugging Priority
    Horizontal: 1000

Content Compression Resistance Priority:
    Horizontal: 1000

结果:

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

The only other issue would be if the text in the right-side label exceeds the full width of the view -- but you haven't indicated that you might need that much text.

这篇关于带有两个标签(一个多行标签,一个单行)的水平UIStackView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:56