Search code examples
swiftautolayoutuikitconstraintsuistackview

Why does pinning a UIStackView on all edges cause an ambiguous constraint Error?


The following code is an attempt to programatically pin a UIStackView on all edges - ie make it full screen. What is it about these seemingly simple constraints that cause this error?

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let stack = UIStackView(arrangedSubviews: [])

        view.addSubview(stack)
        NSLayoutConstraint.activate([
            stack.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            stack.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            stack.topAnchor.constraint(equalTo: view.topAnchor),
            stack.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }

}

Constraint error printed in debugger (link to WTFAutoLayout):

(
    "<NSAutoresizingMaskLayoutConstraint:0x600003407840 h=--& v=--& UIStackView:0x7f97e240f020.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000340ccd0 H:|-(0)-[UIStackView:0x7f97e240f020]   (active, names: '|':UIView:0x7f97e6002d90 )>",
    "<NSLayoutConstraint:0x60000340dd10 UIStackView:0x7f97e240f020.trailing == UIView:0x7f97e6002d90.trailing   (active)>",
    "<NSLayoutConstraint:0x6000034073e0 'UIView-Encapsulated-Layout-Width' UIView:0x7f97e6002d90.width == 414   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x60000340dd10 UIStackView:0x7f97e240f020.trailing == UIView:0x7f97e6002d90.trailing   (active)>

Solution

  • Add the below code as well,

    stack.translatesAutoresizingMaskIntoConstraints = false