Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing constraints that were added programatically

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))
like image 586
Sargot Avatar asked Oct 28 '25 19:10

Sargot


2 Answers

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
like image 196
Mr. Xcoder Avatar answered Oct 31 '25 09:10

Mr. Xcoder


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
like image 22
Leo Avatar answered Oct 31 '25 07:10

Leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!