read

I have a 2014 post in Objective-C, and quite a bit has changed since then. We now have Swift 5, and layout anchors (a short introduction below).

A comprehensive tutorial comes from theswiftdev, ranging from where to create the constraints, including how to animate them.

However, I find his code on animating constraints differ slightly from my style.

How I animate constraints

Similar to how I do it in 2014, I change the constraints within the animation block.

UIView.animate(withDuration: 0.25) {
    // Make all constraint changes here
    // For example:
    someViewConstraint.constant = 80
    self.view.layoutIfNeeded()
}

theswiftdev’s gist does it before the animation block. It also works, but that is simply due to the way layout engine process the changes.

There are times you might even have to call view.layoutIfNeeded() before the animation, to make sure the animation starts at the right place.

Changing your final constraints within the animation block will ensure that is the final state.

Layout Anchor

Layout anchor was introduced in iOS 9, making the APIs for auto layout much nicer (to code with).

The NSLayoutAnchor class is a factory class for creating NSLayoutConstraint objects using a fluent API. Use these constraints to programatically define your layout using Auto Layout.

A simple example of setting up a subview to have the same safe edges as it’s superview:

view.addSubview(subview)
NSLayoutConstraint.activate([
    subview.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor),
    subview.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor),
    subview.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
    subview.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
])

It is much shorter than init-ing each NSLayoutConstraint with 7 parameters. Oh, and always better than Visual Language Format.

NSLayoutConstraint.activate is the magic method to activate all those constraints.

NSLayoutConstraint.deactivate is removing the constraints, and will be useful in animation.


Image

@samwize

¯\_(ツ)_/¯

Back to Home