Marco Schließer
Marco Schließer

Reputation: 25

iOS Animate height constraint issue

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?

Upvotes: 2

Views: 1321

Answers (3)

Payal
Payal

Reputation: 31

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

It should be like this.

Upvotes: 3

NotABot
NotABot

Reputation: 526

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()
})

Upvotes: 1

Sivajee Battina
Sivajee Battina

Reputation: 4174

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()
}

Upvotes: 1

Related Questions