1

In viewDidLoad I declared a constraint and added it to the UIViewController this way:

var constraintButtonPlay = NSLayoutConstraint (item: buttonPlay, 
attribute: NSLayoutAttribute.Bottom, 
relatedBy: NSLayoutRelation.Equal, 
toItem: self.view, 
attribute: NSLayoutAttribute.Bottom, 
multiplier: 1,
constant: 500)

self.view.addConstraint(constraintButtonPlay)

When a button is pressed, the constraint should update itself. However, this code doesn't work:

@IBAction func buttonTest(sender: AnyObject) {

    var constraintButtonPlay = NSLayoutConstraint (item: buttonPlay, 
attribute: NSLayoutAttribute.Bottom, 
relatedBy: NSLayoutRelation.Equal, 
toItem: self.view, 
attribute: NSLayoutAttribute.Bottom, 
multiplier: 1,
constant: -500)

}

Now, I realize that declaring the variable another time isn't the ideal solution. So is there a way to declare it once and the call it whenever in the @IBAction?

Why is the @IBAction code not updating the constraint?

Cesare
  • 9,139
  • 16
  • 78
  • 130

1 Answers1

1

You are declaring two local variables in two different scopes, so they are actually two distinct objects and they are not related at all, even though you gave them the same name.

Try storing the reference of the constraint in a property after you create it in viewDidLoad.

Siyu Song
  • 897
  • 6
  • 21
  • Thank you. This question solved my issue entirely: http://stackoverflow.com/a/28129173/1135714. I just needed to create a global variable like this one `var constraint:NSLayoutConstraint!` and then use it in the methods. ` – Cesare Jan 24 '15 at 19:59