Search code examples
iosswiftautolayout

Updating a Constraint Multiple Times


In my Swift app, I need to update an AutoLayout constraint multiple times, so I have a function which does this. I'm having an issue with this constraint not being updated sometimes, and I've narrowed down the issue to being that it updates the first time the function is called, but not if that function is called again.

The code from the function looks like this:

let verticalSpace = NSLayoutConstraint(item: self.prompt, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 10)
NSLayoutConstraint.activate([verticalSpace])

Does anyone know what could be causing this? Is there something which needs to be done in order to update a function multiple times?


Solution

  • You cannot have "competing" constraints. If you set the verticalSpace to 10, then set another verticalSpace to 20, which constraint should be used?

    What you need to do is remove the existing constraint (or deactivate it), and then add/activate your new constraint.

    Or...

    Create your verticalConstraint and save a reference to it... then when you want to change it you can change the .constant however you wish.