以编程方式将视图添加到 UIStackView

Programmatically adding views to a UIStackView

我正在尝试将两个动态 UILabels 添加到 UIStackLabel。目标是使两个标签在视图中间水平居中。

两个UILabels是:

var nameLabel: UILabel!
var ageLabel: UILabel!

UIStackView 是:

var stackedInfoView: UIStackView!

我已尝试遵循此 中提供的指南,这样配置我的视图:

nameLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 120.0, height: 24.0))
ageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 80.0, height: 24.0))
nameLabel.text = "Harry Potter"
ageLabel.text = "100"


stackedInfoView = UIStackView(arrangedSubviews: [nameLabel, ageLabel])
stackedInfoView.axis = .horizontal
stackedInfoView.distribution = .equalSpacing
stackedInfoView.alignment = .center
stackedInfoView.spacing = 30.0
stackedInfoView.centerXAnchor.constraint(equalTo: self.extendedNavView.centerXAnchor).isActive = true
stackedInfoView.centerYAnchor.constraint(equalTo: self.extendedNavView.centerYAnchor).isActive = true

self.extendedNavView.addSubview(stackedInfoView) //extendedNavView is configured inside Storyboard

我的问题是,stackedInfoView 不会显示。此外,当我打印它的 frame 时,我得到 {{0, 0}, {0, 0}}。我还收到一堆关于 Unable to simultaneously satisfy constraints.

的错误消息

我在制作 UIStackView 时做错了什么?非常感谢任何指导。

两个问题,

stackedInfoView.centerXAnchor.constraint(equalTo:self.extendedNavView.centerXAnchor).isActive = true
stackedInfoView.centerYAnchor.constraint(equalTo:self.extendedNavView.centerYAnchor).isActive = true

应该放在self.extendedNavView.addSubview(stackedInfoView)之后。因为堆栈视图必须在配置约束之前位于视图层次结构中。

其次,添加stackedInfoView.translatesAutoresizingMaskIntoConstraints = false告诉UIKit你想使用自动布局来设置堆栈视图的位置。

如果 extendedNavView 故事板中没有布局问题,则以下代码应该有效:

override func viewDidLoad() {
    super.viewDidLoad()

    var nameLabel: UILabel!
    var ageLabel: UILabel!

    var stackedInfoView: UIStackView!

    nameLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 120.0, height: 24.0))
    ageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 80.0, height: 24.0))
    nameLabel.text = "Harry Potter"
    ageLabel.text = "100"

    stackedInfoView = UIStackView(arrangedSubviews: [nameLabel, ageLabel])
    stackedInfoView.axis = .horizontal
    stackedInfoView.distribution = .equalSpacing
    stackedInfoView.alignment = .center
    stackedInfoView.spacing = 30.0

    stackedInfoView.translatesAutoresizingMaskIntoConstraints = false

    self.extendedNavView.addSubview(stackedInfoView) //extendedNavView is configured inside Storyboard

    stackedInfoView.centerXAnchor.constraint(equalTo: self.extendedNavView.centerXAnchor).isActive = true
    stackedInfoView.centerYAnchor.constraint(equalTo: self.extendedNavView.centerYAnchor).isActive = true

}