Reputation: 13103
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.
Upvotes: 0
Views: 77
Reputation: 130191
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
.
Upvotes: 1
Reputation: 77690
Use a class-level variable to hold the constraint you want to modify. If you are using storyboards / Interface Builder, you can also assign a constraint as an IBOutlet.
class ViewController: UIViewController {
var constraintToAnimate: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
constraintToAnimate = NSLayoutConstraint(item: some, attribute: fromAttribute, relatedBy: NSLayoutRelation.equal, toItem: some2, attribute: toAttribute, multiplier: multiplier, constant: -5)
constraintToAnimate.isActive = true
}
// later, perhaps in a button tap...
func animateIt() {
constraintToAnimate?.constant = 100
}
}
Upvotes: 0