Mozahler Mozahler -4 years ago 125
iOS Question

How do I add an identifier to auto layout anchor constraints?

I want to add identifiers to all my constraints so I can debug an issue. The problem is that I don’t create all my constraints directly if I use anchors.
I can create a constraint:

let constraint = NSLayoutConstraint(item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 60.0)

but then I’d have to add it to the view, not the heightAnchor (there is no .addConstraint() method associated with UIStackViews)

So how do I add identifiers to the constraints auto-generated by these lines of code:

view.heightAnchor.constraint(equalToConstant: 60.0).isActive = true
view.widthAnchor.constraint(equalToConstant: 60.0).isActive = true

anchors are supposed to make programming auto layout easier, but surely not at the expense of being unable to debug properly?
If I can’t add identifiers, how do I debug my “unsatisfiable” constraints exception?

Answer Source

Your code returns you constraint, so you can add identifier to it like this

let myConstraint = view.heightAnchor.constraint(equalToConstant: 60.0)
myConstraint.identifier = "myIdentifier"
myConstraint.isActive = true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download