繁体   English   中英

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

[英]Layout two UILabels at each end of horizontal UIStackView

我正在尝试在水平UIStackView布局两个UILabel ,但无法正常工作。 如您所见,label2(红色)没有使用label1的剩余宽度。

在此处输入图片说明

您可以在操场上添加以下代码:

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

正如评论者所指出的那样,您需要调整标签的内容拥抱或抗压强度,因为它们的默认值将是相同的值,从而导致自动版式赋予它们相同的优先级和间距。 您还需要将堆栈视图的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

暂无
暂无

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

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