Cesare
Cesare

Reputation: 9419

Update the constant property of a constraint programmatically in Swift?

I want to animate an object, so I declare a constraint and add it to the view. I then update the constant property of the constraint inside an UIView animation. Why doesn't this code move the object?

UIView.animateWithDuration(1, animations: {
     myConstraint.constant = 0   
     self.view.updateConstraints(myConstraint)
})

Upvotes: 38

Views: 51988

Answers (1)

duan
duan

Reputation: 8875

In order to declare an animation, you cannot re-define the constraint and call updateConstraints. You are supposed to change the constant of your constraint and follow the format below:

self.view.layoutIfNeeded()
UIView.animate(withDuration: 1) {
    self.sampleConstraint.constant = 20
    self.view.layoutIfNeeded()
}

Upvotes: 91

Related Questions