2

I have a problem with the animation of a view after changing it's height constraint. In the screenshot, you can see it's initial value of 120.0. enter image description here The animation works but the constraint update from my second view (the blue one) happens directly and not during the animation. This means that second view jumps to the top directly. With the following code, I will animate the change of the height constraint:

UIView.animate(withDuration: 3.0, animations: {
    self.heightConstraint?.constant = 0.0
    self.myLabel.alpha = 0.0
    self.layoutIfNeeded()
})

Does anybody know why?

Fangming
  • 24,551
  • 6
  • 100
  • 90
  • Set the constraint outside of the animation block and just call `layoutIfNeeded` in the animation block. – Paulw11 Jul 10 '17 at 10:53
  • This don't work. I experience the same behaviour. I need to say, that my two views are also in a scroll view. Can this be the reason? – Marco Schließer Jul 10 '17 at 11:04
  • 2
    So i found the error. The problem is, that i subclassed the view and did the animation stuff there. So i need to call self.superview?.layoutIfNeeded() instead of self.layoutIfNeeded() – Marco Schließer Jul 10 '17 at 11:10
  • Possible duplicate of [How do I animate constraint changes?](https://stackoverflow.com/questions/12622424/how-do-i-animate-constraint-changes) – Bhautik Ziniya Jul 10 '17 at 12:44

3 Answers3

3
self.heightConstraint?.constant = 0.0
self.myLabel.alpha = 0.0
UIView.animate(withDuration: 3.0, animations: {
    self.layoutIfNeeded()
})

It should be like this.

Pang
  • 9,564
  • 146
  • 81
  • 122
Payal
  • 31
  • 2
1

For animating constraint changes, you need to write code like below to work.

self.heightConstraint?.constant = 0.0
self.myLabel.alpha = 0.0

UIView.animate(withDuration: 5) {
    self.layoutIfNeeded()
}
Sivajee Battina
  • 4,124
  • 2
  • 22
  • 45
1

You need to call self.layoutIfNeeded() before and after updating constraint constant. Change your code to :

self.layoutIfNeeded()

UIView.animate(withDuration: 3.0, animations: {
    self.heightConstraint?.constant = 0.0
    self.myLabel.alpha = 0.0
    self.layoutIfNeeded()
})
NotABot
  • 516
  • 1
  • 8
  • 27