UIStackView 是非常方便的自动布局控件,但是有个大坑,可能就我自己不知道
let stackView = UIStackView(frame: self.view.bounds)
stackView.backgroundColor = .white
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
self.view.addSubview(stackView)
for _ in 0...5 {
let label = UILabel()
// label.frame.size = CGSize(width: 200, height: 100)
label.text = "jjkkkjkjkjk"
label.backgroundColor = .red
stackView.addArrangedSubview(label)
}
然鹅
let stackView = UIStackView(frame: self.view.bounds)
stackView.backgroundColor = .white
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
self.view.addSubview(stackView)
for _ in 0...5 {
let label = UILabel()
// label.frame.size = CGSize(width: 200, height: 100)
// label.text = "jjkkkjkjkjk"
label.backgroundColor = .red
stackView.addArrangedSubview(label)
}
总结(经过测试并我瞎猜,相关代码就不上了)
- stackView 是容器,设置内部子控件 size 需要使用约束
- stackView 里面对 label 做了 sizeToFit() 操作
- stackView 如果需要空白占位,请用 UILabel,并设置 text 为 “ ”,就 ok 了