Topics

#112: Layout Guides & Anchors ⚓️

Topics

Layout Guides & Anchors were added in iOS 9/OS X 10.11 as a more convenient way to add Auto Layout constraints. Let's dive in.

Layout Guides let us create sort of "invisible boxes" that exist solely for the purpose of layout. Instead of adding "spacer" views or using other such tricks, we can add some layout guides to a view, then add some constraints to them. It's a nice way to avoid needless performance wastes like rendering the dummy "spacer" views, and the code itself ends up being much more readable:

var textContainerGuide = UILayoutGuide()
view.addLayoutGuide(textContainerGuide)

Note: Layout Guides are defined in code using UILayoutGuide on iOS and NSLayoutGuide on OS X.

Anchors are best explained with an example. They allow us to turn verbose code like these manually configured constraints:

NSLayoutConstraint(item: someView,
  attribute: .Leading,
  relatedBy: .Equal,
  toItem: anotherView,
  attribute: .LeadingMargin,
  multiplier: 1.0,
  constant: 0.0
).active = true

NSLayoutConstraint(item: someView,
  attribute: .Trailing,
  relatedBy: .Equal,
  toItem: anotherView,
  attribute: .TrailingMargin,
  multiplier: 1.0,
  constant: 0.0
).active = true

...into a set of much more readable short lines of code (shown below). The new code reads much more easily from left to right, and is much easier to scan and reason about what's going on.

let margins = anotherView.layoutMarginsGuide

someView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
someView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true

UIView, NSView, and UILayoutGuide all have lots of new anchor properties available to make adding constraints to them much simpler than before. We also get a little extra type safety as a bonus.