---
title: "#112: Layout Guides \u0026 Anchors  ⚓️"
url: https://littlebitesofcocoa.com/112-layout-guides-anchors
author: Jake Marsh
date: 2015-10-27
published: 2015-10-27
topics: ["Layout","UIKit"]
description: "Layout Guides \u0026 Anchors were added in iOS 9/OS X 10.11 as a more convenient way to add Auto Layout constraints."
---

# #112: Layout Guides & Anchors  ⚓️

By Jake Marsh, October 27, 2015. HTML: https://littlebitesofcocoa.com/112-layout-guides-anchors

_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:

``` swift
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**:

``` swift
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.

``` swift
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 <i>much</i> simpler than before. We also get a little extra type safety as a bonus.
