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



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

这两个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
}

相关内容

  • 没有找到相关文章

最新更新