Auto Layout With NSLayoutAnchors

NSLayoutConstraints are painful to use in code. NSLayoutConstraint’s initializer takes many parameters. The Visual Format Language gets around the inconvenience of the initializer parameters, but I can never remember the syntax. Either way, making constraints programmatically gets verbose. The essence of the overall view layout gets lost in the boilerplate code noise.

Thankfully in iOS 9 Apple has solved these problems. Now all UIView subclasses (as well as UILayoutGuides which I wrote about already) have a variety of NSLayoutAnchor properties on them. These NSLayoutAnchors are a fluent api that act as factories for NSLayoutConstraints. Now constraints are very easy to set up.

nautical anchor
Nautical anchors are still superior to NSLayoutAnchors.

Here’s an example of how you would align the tops of two UILabels:

The various NSLayoutAnchor functions provide overloads that can make use of constants too:

That code anchors the top of the UILabels 20 points below the top of the parent UIView. The various “constraintEqualToAnchor” functions return an inactive NSLayoutConstraint instance. You can grab a reference to it for mutation later. If that’s not necessary, you can just set it to active inline with .active = true.

Here are the NSLayoutAnchor properties on UIView:

  • centerXAnchor
  • centerYAnchor
  • bottomAnchor
  • firstBaselineAnchor
  • heightAnchor
  • lastBaselineAnchor
  • leadingAnchor
  • leftAnchor
  • rightAnchor
  • topAnchor
  • trailingAnchor
  • widthAnchor

It should also be noted that there are a few variants of the “constraint” factory functions that allow you to create constraints with <= or >= relationships, setting dimensions to constant values, and using multipliers for relative values.

Here’s a playground with a layout out a red, yellow, and green button vertically inside of a parent UIView to better see this in action:

Here’s the UIView hierarchy that it created.

Playground output
Views created by the playground.

Feel free to fork the actual playground repo on GitHub if you so desire.