Reputation: 83
I read many topics about how to remove constraints that were added through the storyboard, drag outlet and then remove etc. but how I can remove constraints that were added programmatically? For example
firstView.topAnchor.constraints(equalTo: secondView.bottomAnchor, constant: 15).isActive = true
how can I deactivate it and then enable it again if needed. Maybe it should be something like?
firstView.removeConstraint(firstView.topAnchor.constraints(equalTo: secondView.bottomAnchor))
Upvotes: 3
Views: 8888
Reputation: 356
You need to keep a reference to your constraint.
let constraintName: NSLayoutConstraint = firstView.topAnchor.constraint(equalTo: secondView.bottomAnchor, constant: 15)
constraintName.isActive = true
Disable it when you don't need it.
constraintName.isActive = false
Enable it when you want it back.
constraintName.isActive = true
Upvotes: 4
Reputation: 1906
Remove constraints will be deprecated in future.
Here is the alternate way to do the same.
Enable/Disable constraints do with below methods
Objective-C
viewHeightConstraint.active = YES; // Enable
viewHeightConstraint.active = NO; // Disable
Swift
viewHeightConstraint.isActive = true // Enable
viewHeightConstraint.isActive = false // Disable
Upvotes: -3
Reputation: 4795
You should assign your constraint to a property in your ViewController
. And then set .isActive
to false
instead of true.
Your code should look like this:
let myConstraint = firstView.topAnchor.constraint(equalTo: secondView.bottomAnchor, constant: 15)
Now, to activate it:
myConstraint.isActive = true
And to disable it:
myConstraint.isActive = false
Upvotes: 8