Cesare
Cesare

Reputation: 9419

How do I declare a constraint programmatically once and call it whenever it's needed in Swift?

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?

Upvotes: 1

Views: 720

Answers (1)

Siyu Song
Siyu Song

Reputation: 917

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.

Upvotes: 1

Related Questions