在水平UIStackView的每一端布置两个UILabel

时间:2017-12-01 14:54:55

标签: ios uistackview

我试图在水平UILabel中布置两个UIStackView,但我无法让它工作。如您所见,label2(红色)未使用label1的剩余宽度。

enter image description here

您可以在Playground中添加以下代码:

import UIKit
import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.backgroundColor = .green

let labelStackView = UIStackView()

labelStackView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
labelStackView.frame = view.bounds

view.addSubview(labelStackView)

labelStackView.distribution = .equalSpacing
labelStackView.alignment = .lastBaseline
labelStackView.spacing = 10

let label1 = UILabel()
label1.backgroundColor = .blue
label1.numberOfLines = 0
label1.text = "Hej Hej Hej"

let label2 = UILabel()
label2.backgroundColor = .red
label2.numberOfLines = 0
label2.text = "Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej"
label2.textAlignment = .right

labelStackView.addArrangedSubview(label1)
labelStackView.addArrangedSubview(label2)

PlaygroundPage.current.liveView = view

1 个答案:

答案 0 :(得分:1)

评论者指出,您需要调整标签的内容拥抱或压缩阻力,因为它们默认为相同的值,导致自动布局给予它们相同的优先级和间距。您还需要将堆栈视图的distribution更改为fillProportionally。以下对我有用:

let view = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.backgroundColor = .green

let labelStackView = UIStackView()

labelStackView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
labelStackView.frame = view.bounds

view.addSubview(labelStackView)

labelStackView.distribution = .fillProportionally
labelStackView.alignment = .lastBaseline
labelStackView.spacing = 10

let label1 = UILabel()
label1.backgroundColor = .blue
label1.numberOfLines = 0
label1.text = "Hej Hej Hej"
label1.setContentHuggingPriority(UILayoutPriority(1000), for: .horizontal)

let label2 = UILabel()
label2.backgroundColor = .red
label2.numberOfLines = 0
label2.text = "Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej Hej"
label2.textAlignment = .right

labelStackView.addArrangedSubview(label1)
labelStackView.addArrangedSubview(label2)

PlaygroundPage.current.liveView = view