Search code examples
swiftlayoutsubviewsanimatewithduration

Why layoutIfNeeded() allows to perform animation when updating constraints?


I have two states of UIView:

enter image description here enter image description here

I have animation between them using @IBaction for button:

@IBAction func tapped(sender: UIButton) {
    flag = !flag
    UIView.animateWithDuration(1.0) {
        if self.flag {
            NSLayoutConstraint.activateConstraints([self.myConstraint])
        } else {
            NSLayoutConstraint.deactivateConstraints([self.myConstraint])
        }
        self.view.layoutIfNeeded() //additional line
    }
}

Animation is working only when I add additional line:

But when I remove that line, then my UIView is updated but without any animation, it happens immediately.

Why this line makes such difference? How is it working?


Solution

  • As I understand it, changing a constraint doesn't update the layout of your views right away. It queues the changes, and they only take place the next time the system updates layout.

    By putting layoutIfNeeded inside your animation block it forces the view changes to be applied during the animation block. Otherwise they take place later, after the animation has been set up.