简体   繁体   English

如何向 StackView 的子视图内的视图添加约束

[英]How to add constraints to a view inside a subview of a StackView

In my test program there is a vertical stack view, in its third subview (the green one at the bottom) I want to add a red rectangle at its center.在我的测试程序中有一个垂直堆栈视图,在其第三个子视图(底部的绿色)中,我想在其中心添加一个红色矩形。 I tried anchoring to centerXAnchor , and centerXAnchor but it doesn't work.我尝试锚定到centerXAnchorcenterXAnchor但它不起作用。 I suspect it's because the green view doesn't use X and Y anchor as its size and position are managed by the vertical stack view.我怀疑这是因为绿色视图不使用 X 和 Y 锚点,因为它的大小和位置由垂直堆栈视图管理。 What would be the correct way to center the red rectangle inside the green view?在绿色视图中居中红色矩形的正确方法是什么? Here is my codes and screenshots:这是我的代码和屏幕截图:

class ViewController: UIViewController {
    @IBOutlet var greenView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let testView = UIView(frame: CGRect(x: 0,y: 0,width: 50,height: 50))
        testView.backgroundColor = .red
        greenView.addSubview(testView)
        greenView.translatesAutoresizingMaskIntoConstraints = false

        testView.centerXAnchor.constraint(equalTo: greenView.centerXAnchor).isActive = true
        testView.centerYAnchor.constraint(equalTo: greenView.centerYAnchor).isActive = true
    }
}

The is the storyboard.这是故事板。 The only constraints are First View height = Second View Height, and Green View height = 0.8 StackView Height:唯一的限制是 First View height = Second View Height 和 Green View height = 0.8 StackView Height:

这是故事板

This is the result:这是结果:

这是结果

the culprit of this bug is greenView.translatesAutoresizingMaskIntoConstraints = false what I am doing is setting width ,height with Anchor api这个错误的罪魁祸首是greenView.translatesAutoresizingMaskIntoConstraints = false我正在做的是使用 Anchor api 设置宽度、高度

let testView = UIView(frame: CGRect(x: 0,y: 0,width: 0,height: 0))
        testView.backgroundColor = .white
        greenView.addSubview(testView)
        testView.translatesAutoresizingMaskIntoConstraints = false

        testView.centerXAnchor.constraint(equalTo: greenView.centerXAnchor).isActive = true
        testView.widthAnchor.constraint(equalToConstant: 50).isActive = true
        testView.heightAnchor.constraint(equalToConstant: 100).isActive = true
        testView.centerYAnchor.constraint(equalTo: greenView.centerYAnchor).isActive = true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM