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

时间:2017-05-10 23:13:51

标签: ios swift autolayout uistackview

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

两个UILabels是:

var nameLabel: UILabel!
var ageLabel: UILabel!

UIStackView是:

var stackedInfoView: UIStackView!

我试图遵循此answer中提供的指南,并按照以下方式配置我的观点:

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时做错了什么?任何指导都非常感谢。

1 个答案:

答案 0 :(得分:6)

两个问题,

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

}