在使用UIStackView时遇到一个奇怪的问题,该问题不允许我在嵌套的UIStackView中添加额外安排的子视图:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
let subViews = [UIColor.gray, UIColor.darkGray, UIColor.lightGray].map { (color) -> UIView in
let v = UIView()
v.backgroundColor = color
return v
}
let redView = UIStackView(arrangedSubviews: subViews)
redView.distribution = .fillEqually
redView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
let blueView = UIView()
blueView.backgroundColor = .blue
let buttons = [UIColor.gray, UIColor.darkGray, UIColor.lightGray].map { (color) -> UIView in
let v = UIView()
v.backgroundColor = color
return v
}
let buttonsView = UIStackView(arrangedSubviews: buttons)
buttonsView.distribution = .fillEqually
buttonsView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
let stackView = UIStackView(arrangedSubviews: [redView, blueView, buttonsView])
view.addSubview(stackView)
stackView.axis = .vertical
stackView.fillSuperview()
}
结果是,我得到了完全拉伸的蓝色视图,而不是预期的行为:
但是当我在底部堆栈视图中保留一个子视图时,它会按预期显示
let buttons = [UIColor.gray].map { (color) -> UIView in
let v = UIView()
v.backgroundColor = color
return v
}
let buttonsView = UIStackView(arrangedSubviews: buttons)
buttonsView.distribution = .fillEqually
buttonsView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true
let stackView = UIStackView(arrangedSubviews: [redView, blueView, buttonsView])
为什么?代码有什么问题?感谢您提供任何帮助或提示,我也尝试在顶部和底部堆栈视图上translatesAutoresizingMaskIntoConstraints = false
,但没有任何运气
答案 0 :(得分:1)
在底部stackview上需要设置
buttonView.heightAnchor.constraint(equalToConstant: 100).isActive = true
代替
buttonView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true