Search code examples
swiftautolayoutios-autolayout

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. 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. 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:

Here is the story board

This is the result:

Here is the result


Solution

  • the culprit of this bug is greenView.translatesAutoresizingMaskIntoConstraints = false what I am doing is setting width ,height with 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