Update the constant property of a constraint programmatically in Swift?

51,141

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()
}
Share:
51,141
Cesare
Author by

Cesare

Updated on April 29, 2020

Comments

  • Cesare
    Cesare almost 4 years

    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)
    })
    
  • Mudit Jaju
    Mudit Jaju about 8 years
    self.view.layoutIfNeeded() was exactly what I was looking for! Thanks a lot for this. Just a doubt .. does it have some kind of performance hit as well ?
  • duan
    duan about 8 years
    @MuditJaju If its not in UITableView,usually there's no performance problem.