Search code examples
iosswiftautolayoutnslayoutconstraint

Unable to get constraints of NSLayoutConstraint


This is my code:

let b = NSLayoutConstraint(item: some, attribute: fromAttribute, relatedBy: NSLayoutRelation.equal, toItem: some2, attribute: toAttribute, multiplier: multiplier, constant: -5)
b.isActive = true
self.layoutIfNeeded()
print(b.constant)
print(some.constraints.first(where: {$0.constant == -5 }))

And this is my print:

-5.0
nil

How can I get that constraint back in code? Why does it print out nil? I want to animate the constraint's constant later on. Thanks.


Solution

  • Let's start with the core question:

    How can I get that constraint back in code?

    Ideally, you don't. You save it to a variable when you create it, e.g.:

    var myConstraint: NSLayoutConstraint?
    
    func x() {
       let b = NSLayoutConstraint(...)
       ...
       myConstraint = b
    }
    

    Why does it print out nil?

    When setting isActive = true, the constraint is added to the closest common superview. For example, if A is a superview of B and you have a same-width constraint, then the constraint is added to A and it won't be present on B.

    The constraint will be added to some only if some2 is a subview of some.