Animating UIView by changing constraints

That’s one of the most fun and easiest animations you can do.

First, let’s make sure we know what constraint to change: you’ll have to make sure you either have the constraint as an @IBOutlet or -if you’ve added in code- make sure you add an identifier to it. 

Then you’ll trigger a constant change within an animation block, in this first example we’re using the identifier to find the right constraint:

        UIView.animate(withDuration: 0.2) {

            let identifyTheRightConstraint = self.parent!.view.constraints.filter{ $0.identifier == “distanceOfMessageToTop” }

            if let constraint = identifyTheRightConstraint.first{

                constraint.constant = 0

            }

            self.parent!.view.layoutIfNeeded()

 

        }

 

Or this is you’re using an @IBOutlet

        UIView.animate(withDuration: 0.2) {

 

            IBOutletConstraint.constant = 0

 

            self.parent!.view.layoutIfNeeded()

 

        }

 

It’s very important that you’re triggering layoutIfNeeded() for the parent view of the view you’re changing the constraints on. And that’s it!  

Questions / comments / suggestions? @MarcMasVi 

Marc