38

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)
})
Cesare
  • 9,139
  • 16
  • 78
  • 130

1 Answers1

91

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()
}
duan
  • 8,515
  • 3
  • 48
  • 70
  • 3
    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 ? – Mudit Jaju Apr 03 '16 at 08:51
  • 3
    @MuditJaju If its not in UITableView,usually there's no performance problem. – duan Apr 03 '16 at 09:27