UIStackView 的注意事项
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) }
然鹅
这样就不行了, stackView 一片空白
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 了
作者:在知识的海洋里溺水身忘的小不懂
https://www.jianshu.com/p/6a9fa51575a0