---
title: "#131: Declarative Auto Layout with Cartography 📏📐"
url: https://littlebitesofcocoa.com/131-declarative-auto-layout-with-cartography
author: Jake Marsh
published: 2015-11-23
topics: ["Layout","Libraries"]
description: "We've covered Auto Layout quite bit, but so far we've only been using the classes and APIs that Apple ships. Today we'll start checking out some third-party..."
---

# #131: Declarative Auto Layout with Cartography 📏📐

By Jake Marsh, November 23, 2015. HTML: https://littlebitesofcocoa.com/131-declarative-auto-layout-with-cartography

We've covered [Auto Layout][1] quite bit, but so far we've only been using the **classes** and **APIs** that Apple ships. Today we'll start checking out some third-party libraries that can improve our experience when working with _Auto Layout_.

First up is [Cartography][2] from [Robert Böhnke][3]. Let's take a look:

_Cartography_ takes the form of a sort of DSL for _Auto Layout_. It allows us to take conventional **UIKit** code like this:

``` swift
view.addConstraint(
  NSLayoutConstraint(
    item: editButton,
    attribute: .Right,
    relatedBy: .Equal,
    toItem: launchButton,
    attribute: .Left,
    multiplier: 1.0,
    constant: -8.0
  )
)
```

And express it using a new `constrain` **function**:

``` swift
constrain(editButton, launchButton) { editButton, launchButton in
  editButton.right == launchButton.left - 8
}
```

We can pass in up to 5 **UIView** or **NSView** instances at once, then a **closure**. In that **closure**, we'll use `==`, `>=`, or `<=` **operators** to define **constraints** upon the **attributes** of the **view** instances. This can really help improve readability:

``` swift
constrain(viewA) { a in
  // fixed sizes:
  a.height == 44

  // centering inside a parent view:
  a.centerX == a.superview!.centerX

  // inequalities:
  a.top >= a.superview!.top + 10
}
```

But wait, there's more! We can capture the created **constraints** like this:

``` swift
let group = constrain(launchButton) { button in
  button.top  == button.superview!.top
  button.left == button.superview!.left
}
```

Then move that button by <i>replacing</i> the captured **constraints** like this:

``` swift
constrain(launchButton, replace: group) { button in
  button.bottom == button.superview!.bottom
  button.right  == button.superview!.right
}
```

Additionally, it provides helper **functions** for aligning and distributing:

``` swift
constrain(viewA, viewB, viewC) { viewA, viewB, viewC in
  align(top: viewA, viewB, viewC)
  distribute(by: 8, horizontally: viewA, viewB, viewC)
}
```

[Cartography][2] has shortcuts for **edges** and **sizes**, **operators** for setting **priorities**, and much more! More info can be found at [git.io/cartography][2].

[1]: https://littlebitesofcocoa.com/topics/3-layout?v=l
[2]: http://git.io/cartography
[3]: https://github.com/robb
