How to Animate Auto Layout Constraints

Make it look smooth and nice

Steven Curtis
3 min readMay 2, 2020


Photo by Hal Gatewood on Unsplash

Animating constraints is one of those things that I’ve heard are tricky. Activate and reactivate constraints? You can do it! Just read on for the details.

Difficulty: Beginner | Easy | Normal | Challenging


The task

I’m going to create an attractive green button, and let it move around the screen according to it’s constraints.

I’ve set up the button (with fun constraints) in loadView(). Now I’ve set up this project in Playgrounds. This means that you’ll need import PlaygroundSupport and since I’m calling my View Controller myViewController (because I’m excellent at naming) I’ll need PlaygroundPage.current.liveView = MyViewController().

At the bottom of this page is the working Playground code — skip ahead to there if you choose not to have the rather excellent

Setting properties for the constraints

I’m going to put 4 constraints around my UIButton — these are going to define the height, width, XConstraint and YConstraint so effectively we are setting the size, X and Y position of the UIButton.

var buttWidthConstraint: NSLayoutConstraint!
var buttHeightConstraint: NSLayoutConstraint!
var buttXConstraint: NSLayoutConstraint!
var buttYConstraint: NSLayoutConstraint!

Setting the initial constraints

Assuming we have correctly set up the UIButton (we have…look at the full code below) we will set up the constraints shown below:

let buttWidthConstraint = myButt.widthAnchor.constraint(equalToConstant: 100)
let buttHeightContraint = myButt.heightAnchor.constraint(equalToConstant: 100)
let buttXConstraint = myButt.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
let buttYConstaint = myButt.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)