Search code examples
iosswiftnslayoutconstraint

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.


Solution

  • 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()