使用乘数在 UIStackView 中按比例设置视图 - swift - 以编程方式

Proportionally set views inside UIStackView using multiplier - swift - programmatically

我正在设置一个填充整个容器视图的垂直 stackView。

在容器视图初始化程序中,我放置了这段代码,旨在为排列的子视图设置比例高度:

    view1.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.2).isActive = true
    view2.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.6).isActive = true
    view3.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.2).isActive = true
    
    
    let stackView = UIStackView(arrangedSubviews: [view1, view2, view3])
    
    stackView.axis = .vertical
    
    

    addSubview(stackView)
    stackView.fillSuperview()

当我尝试 运行 时收到此错误:

Unable to activate constraint with anchors [...] because they have no common ancestor. Does the constraint or its anchors reference items in different view hierarchies? That's illegal.'

首先添加排列好的子视图,然后激活stackView相关的约束。

let view1 = UIView()
let view2 = UIView()
let view3 = UIView()

view1.backgroundColor = .red
view2.backgroundColor = .blue
view3.backgroundColor = .green

let stackView = UIStackView(arrangedSubviews: [view1, view2, view3])
stackView.frame = CGRect(x: 0, y: 0, width: 40, height: 100)
stackView.axis = .vertical

view1.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 0.2).isActive = true
view2.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 0.6).isActive = true
view3.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 0.2).isActive = true