Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeConstraint() not removing constraint

I have a weird problem. I want to change a constraint in certain conditions, but removeConstraint doesn't work. The constraint doesn't get removed.

Here's the code:

backButton.translatesAutoresizingMaskIntoConstraints = false
view.removeConstraint(constLabelTop)
let constNew = NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: backButton, attribute: .CenterY,multiplier: 1, constant: 0)
view.addConstraint(constNew)

The constraint constLabelTop is a constraint which sets the top of the label a few points above the backButton. Why doesn't it work?

The new constraint clashes with the old one and the backButton gets squashed.

I tried backButton.removeConstraint too and didn't work either.

like image 946
Lawrence413 Avatar asked May 11 '16 17:05

Lawrence413


People also ask

How do I delete a constraint in Swift?

Just select the view you want to remove a constraint from and open the size inspector. You should see a list of all the constraints. Select the one you want to delete, and press the delete key.

How do I uninstall Nslayoutconstraint?

The way to remove constraints is to use the removeConstraint method on a UIView .


1 Answers

Try this:

backButton.translatesAutoresizingMaskIntoConstraints = false
constLabelTop.active = false
NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: backButton, attribute: .CenterY,multiplier: 1, constant: 0).active = true
self.view.layoutIfNeeded()
like image 80
Khuong Avatar answered Oct 12 '22 22:10

Khuong