我的Swift代码中有stackview
let comment1 = Comment(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let comment2 = Comment(frame: CGRect(x: 0, y: 100, width: 100, height: 100))
let comment3 = Comment(frame: CGRect(x: 0, y: 200, width: 100, height: 100))
let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing = 16.0
stackView.backgroundColor = .green
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(comment1)
stackView.addArrangedSubview(comment2)
stackView.addArrangedSubview(comment3)
view.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
Comment
是UIView的子类。问题是stackView和子视图都是可见的。为什么?
答案 0 :(得分:1)
我刚用你的代码测试过。您的约束似乎存在问题。我添加了heightAnchor和widthAchor的约束,导致在不可见之前显示stackView。 下面是代码,也是附加的图像。
注意:因为我没有评论视图所以我只使用了UIView。您需要将其更改回评论
let comment1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let comment2 = UIView(frame: CGRect(x: 0, y: 100, width: 100, height: 100))
let comment3 = UIView(frame: CGRect(x: 0, y: 200, width: 100, height: 100))
comment1.heightAnchor.constraint(equalToConstant: 100).isActive = true
comment1.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
comment2.heightAnchor.constraint(equalToConstant: 100).isActive = true
comment2.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
comment3.heightAnchor.constraint(equalToConstant: 100).isActive = true
comment3.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
comment1.backgroundColor = UIColor.blue
comment2.backgroundColor = UIColor.green
comment3.backgroundColor = UIColor.red
let stackView = UIStackView()
stackView.axis = UILayoutConstraintAxis.vertical
stackView.distribution = UIStackViewDistribution.equalSpacing
stackView.alignment = UIStackViewAlignment.center
stackView.spacing = 16.0
stackView.backgroundColor = .green
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.addArrangedSubview(comment1)
stackView.addArrangedSubview(comment2)
stackView.addArrangedSubview(comment3)
self.view.addSubview(stackView)
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true