Auto Layout Visual Format Language Tutorial

Darren Ferguson
VisualFormatIcon

Learn how to layout elements using ASCII art!

Auto Layout’s Visual Format Language (VFL) allows you to define constraints by using an ASCII-art formatted string.

With a single line of code, you can specify multiple constraints in either the horizontal or vertical direction. This can save a lot of code compared to creating constraints one at a time.

In this tutorial, you and VFL will become buddies as you do the following:

  • Construct horizontal and vertical constraints
  • Use views definitions inside your VFL string
  • Use metrics constants inside your VFL string
  • Use layout options to position interface elements relative to others
  • Use layout guides to take top and bottom view edges into consideration
Note: Updated for Xcode 7.3, iOS 9.3, and Swift 2.2 on 04-01-2016

Note: this tutorial assumes you’re well acquainted with Auto Layout. If you’re fairly new to it, you may want to start with Auto Layout Tutorial Part 1: Getting Started and Auto Layout Tutorial Part 2: Constraints.

Getting Started

Start by downloading the starter project for this tutorial, which comprises a basic welcome screen for a fledgling social networking app — Grapevine. Build and run (Product \ Run or ⌘R) the project in Xcode; you’ll see the following (to rotate the simulator go to Hardware \ Rotate Right):

Initial screen

Well, that’s a hot mess. Why is this happening and what are you going to do about it?

All the interface elements are currently pinned to the top and left of the view, and this is the result of them having no associated Auto Layout constraints. You’ll make the view much prettier during the course of this tutorial.

Open Main.storyboard and look at the interface elements. Note that the interface elements are set with Auto Layout constraints that are removed at compile time. You wouldn’t do this in a real project, but this saves you having to enter a lot of view creation code :]

Next, open ViewController.swift and have a look inside. At the top, you’ll see outlets connected to the Interface Builder (IB) interface elements inside Main.storyboard and a property that’ll replace constraints at runtime.

There’s not much else to talk about in the app at this point, but there is a lot good stuff to learn about VFL!

Visual Format String Grammar

Before you dive into setting up layouts and constraints, you’ll need some background knowledge on the VFL format string.

First thing to know: The format string can be split into the following components:

VisualFormatLanguageOptionsImage

Here’s a step-by-step explanation of the VFL format string:

  1. Direction of your constraints, not required. Can have the following values:

    • H: indicates horizontal orientation.
    • V: indicates vertical orientation.
    • Not specified: Auto Layout defaults to horizontal orientation.
  2. Leading connection to the superview, not required.

    • Spacing between the top edge of your view and its superview’s top edge (vertical)
    • Spacing between the leading edge of your view and its superview’s leading edge (horizontal)
  3. View you’re laying out, is required.
  4. Connection to another view, not required.
  5. Trailing connection to the superview, not required.

    • Spacing between the bottom edge of your view and its superview’s bottom edge (vertical)
    • Spacing between the trailing edge of your view and its superview’s trailing edge (horizontal)

There are two special (orange) characters in the image and their definition is below:

  • ? component is not required inside the layout string.
  • * component may appear 0 or more times inside the layout string.

Available Symbols

VFL uses a number of symbols to describe your layout:

  • | superview
  • - standard spacing (usually 8 points; value can be changed if it is the spacing to the edge of a superview)
  • == equal widths (can be omitted)
  • -20- non standard spacing (20 points)
  • <= less than or equal to
  • >= greater than or equal to
  • @250 priority of the constraint; can have any value between 0 and 1000

    • 250 - low priority
    • 750 - high priority
    • 1000 - required priority

Example Format String

  H:|-[icon(==iconDate)]-20-[iconLabel(120@250)]-20@750-[iconDate(>=50)]-|

Here's a step-by-step explanation of this string:

  • H: horizontal direction.
  • |-[icon icon's leading edge should have standard distance from its superview's leading edge.
  • ==iconDate icon's width should be equal to iconDate's width.
  • ]-20-[iconLabel icon's trailing edge should be 20 points from iconLabel's leading edge.
  • [iconLabel(120@250)] iconLabel should have a width of 120 points. The priority is set to low, and Auto Layout can break this constraint if a conflict arises.
  • -20@750- iconLabel's trailing edge should be 20 points from iconDate's leading edge. The priority is set to high, so Auto Layout shouldn't break this constraint if there's a conflict.
  • [iconDate(>=50)] iconDate's width should be greater than or equal to 50 points.
  • -| iconDate's trailing edge should have standard distance from its superview's trailing edge.

got_it

Now that you have a basic understanding of the VFL -- and more importantly the format string -- it's time to put that knowledge to use.

Creating Constraints

Apple provides the class method constraintsWithVisualFormat on NSLayoutConstraint to create constraints. You'll use it to create constraints programmatically inside of Grapevine.

Open ViewController.swift in Xcode, and add the following code to viewDidLoad():

appImageView.hidden = true
welcomeLabel.hidden = true
summaryLabel.hidden = true
pageControl.hidden = true

This code hides all interface elements except the iconImageView, appNameLabel and skipButton. Build and run your project; you should see the following:

Grapevine-Hidden-Icons

Cool. You've cleared the cluttery interface elements, now add the following code to the bottom of viewDidLoad():

// 1
let views = ["iconImageView": iconImageView,
  "appNameLabel": appNameLabel,
  "skipButton": skipButton]

// 2
var allConstraints = [NSLayoutConstraint]()

// 3
let iconVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-20-[iconImageView(30)]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += iconVerticalConstraints

// 4
let nameLabelVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-23-[appNameLabel]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += nameLabelVerticalConstraints

// 5
let skipButtonVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-20-[skipButton]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += skipButtonVerticalConstraints

// 6
let topRowHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-15-[iconImageView(30)]-[appNameLabel]-[skipButton]-15-|",
  options: [],
  metrics: nil,
  views: views)
allConstraints += topRowHorizontalConstraints

// 7
NSLayoutConstraint.activateConstraints(allConstraints)

Here's a step-by-step explanation of the above code:

  1. Create a views dictionary that holds string representations of views to resolve inside the format string.
  2. Create a mutable array of constraints. You'll build this up in the rest of the code.
  3. Set up vertical constraints for the iconImageView, placing its top edge 20 points from its superview's top edge, with a height of 30 points.
  4. Set up vertical constraints for the appNameLabel, placing its top edge 23 points from its superview's top edge.
  5. Set up vertical constraints for the skipButton, placing its top edge 20 points from its superview's top edge.
  6. Set up horizontal constraints for all three interface elements. The iconImageView's leading edge is placed 15 points from the leading edge of its superview, with a width of 30 points. Next, a standard spacing of 8 points is placed between the iconImageView and appNameLabel. Next, a standard spacing of 8 points is placed between the appNameLabel and skipButton. Finally, the skipButton's trailing edge is placed 15 points from the trailing edge of its superview.
  7. Activate the layout constraints using the class method activateConstraints(_:) on NSLayoutConstraint. You pass in the allConstraints array you've been adding to all this time.

Note: The string keys inside the views dictionary must match the view strings inside the format string. If they don't, Auto Layout won't be able to resolve the reference and will crash at runtime.

Build and run your project. How do the interface elements look now?

Grapevine-Horizontal-Layout

Hey, look at that! You've already made it prettier.

Now stick with it here, that first part was just a teaser. You've got a lot of code to write, but it'll be worth it at the end.

Next, you'll lay out the remaining interface elements. First, you need to remove the code you originally added to viewDidLoad(). I know, I know...you just put it there. Delete these lines:

appImageView.hidden = true
welcomeLabel.hidden = true
summaryLabel.hidden = true
pageControl.hidden = true

Removing this reverts the display so it shows the remaining interface elements that you previously hid from yourself.

Next, replace your current views dictionary definition with the following:

let views = ["iconImageView": iconImageView,
  "appNameLabel": appNameLabel,
  "skipButton": skipButton,
  "appImageView": appImageView,
  "welcomeLabel": welcomeLabel,
  "summaryLabel": summaryLabel,
  "pageControl": pageControl]

Here you've added view definitions for the appImageView, welcomeLabel, summaryLabel and pageControl, which can now be used inside the VFL format string.

Add the following to the bottom of viewDidLoad(), above the activateConstraints() call:

// 1
let summaryHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-15-[summaryLabel]-15-|",
  options: [],
  metrics: nil,
  views: views)
allConstraints += summaryHorizontalConstraints

let welcomeHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-15-[welcomeLabel]-15-|",
  options: [],
  metrics: nil,
  views: views)
allConstraints += welcomeHorizontalConstraints

// 2
let iconToImageVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[iconImageView]-10-[appImageView]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += iconToImageVerticalConstraints

// 3
let imageToWelcomeVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[appImageView]-10-[welcomeLabel]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += imageToWelcomeVerticalConstraints

// 4
let summaryLabelVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[welcomeLabel]-4-[summaryLabel]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += summaryLabelVerticalConstraints

// 5
let summaryToPageVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[summaryLabel]-15-[pageControl(9)]-15-|",
  options: [],
  metrics: nil,
  views: views)
allConstraints += summaryToPageVerticalConstraints

Here's a step-by-step explanation of the above:

  1. Set up horizontal constraints for the summaryLabel and welcomeLabel, placing them 15 points from the leading and trailing edges of their superview.
  2. Set up vertical constraints for the icon to the app image, with spacing of 10 points
  3. Set up vertical constraints for the app image to the welcome label, with spacing of 10 points
  4. Set up vertical constraints between the welcome label and summary label, with a spacing of 4 points
  5. Set up vertical constraints between the summary label and the page control, with a spacing of 15 points and a height of 9 points for the page control, then spacing of 15 points to the superview

Build and run your project; how do the interface elements look?

Grapevine layout before options

Now you're getting somewhere. No, it's not exactly what you're looking for; some interface elements are laid out correctly, however, others are not. The image and the page control aren't centered.

No-Center-RageMakger

Never fear, the next section will provide you with more ammunition to get the layout to clean up its act.

Layout Options

Layout options provide the ability to manipulate view constraints perpendicular to the current layout orientation being defined.

Applying vertical centering to all views in a horizontal layout orientation by using NSLayoutFormatOptions.AlignAllCenterY is an example of layout options.

You wouldn't use this option in vertical orientation since there's no sense in trying to set all of the views' centers vertically while laying them out vertically, edge by edge. It's also not provided for vertical orientation, so there you go.

Next, you'll see how layout options are useful when it comes to constructing layouts. Remove the following code from viewDidLoad():

let nameLabelVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-23-[appNameLabel]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += nameLabelVerticalConstraints
    
let skipButtonVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-20-[skipButton]",
  options: [],
  metrics: nil,
  views: views)
allConstraints += skipButtonVerticalConstraints

You're just removing the vertical constraints from the appNameLabel and skipButton. Instead, you're going to use the layout options to give them a vertical position.

Find the code that creates topRowHorizontalConstraints and set the options parameter to [.AlignAllCenterY]. It should now look like the following:

let topRowHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-15-[iconImageView(30)]-[appNameLabel]-[skipButton]-15-|",
  options: [.AlignAllCenterY],
  metrics: nil,
  views: views)

You've provided the NSLayoutFormatOption .AlignAllCenterY that takes each view inside the format string and creates layout constraints to align each of them by their vertical centers. This code works since the iconImageView has previously defined vertical layout constraints, including its height. Thus, the appNameLabel and skipButton are vertically centered with the iconImageView.

If you build and run now, the layout will look exactly the same, but you know the code is better :]

Remove the code that creates welcomeHorizontalConstraints and adds it to the constraints array.

This removes the horizontal constraints from the welcomeLabel.

Next, update the options when creating summaryLabelVerticalConstraints definition to the following:

summaryLabelVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[welcomeLabel]-4-[summaryLabel]",
  options: [.AlignAllLeading, .AlignAllTrailing],
  metrics: nil,
  views: views)

This code adds the NSLayoutFormatOptions options .AlignAllLeading and .AlignAllTrailing to the method call. The welcomeLabel and summaryLabel's leading and trailing spacing will be aligned 15 points from the leading and trailing edge of their superview. This occurs because the summaryLabel already has its horizontal constraints defined.

Again, this will give you the same layout as you already had, but in a better way.

Next, update the options when you create summaryToPageVerticalConstraints to match the following:

let pageControlVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[summaryLabel]-15-[pageControl(9)]-15-|",
  options: [.AlignAllCenterX],
  metrics: nil,
  views: views)

Adding this option aligns the views on the center X axis. Do the same for imageToWelcomeVerticalConstraints:

let imageToWelcomeVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[appImageView]-10-[welcomeLabel]",
  options: [.AlignAllCenterX],
  metrics: nil,
  views: views)

Build and run your project; how do the interface elements look?

Grapevine-SublayoutViewHeights

Feeling centered yet? Layout options have taken you closer to that nice user interface you're after.

NSLayoutFormat Options Quick Reference

Here are the options you've used in Grapevine:

  • .AlignAllCenterX -- align interface elements using NSLayoutAttributeCenterX.
  • .AlignAllCenterY -- align interface elements using NSLayoutAttributeCenterY.
  • .AlignAllLeading -- align interface elements using NSLayoutAttributeLeading.
  • .AlignAllTrailing -- align interface elements using NSLayoutAttributeTrailing.

Below are some more of these options:

  • .AlignAllLeft -- align interface elements using NSLayoutAttributeLeft.
  • .AlignAllRight -- align interface elements using NSLayoutAttributeRight.
  • .AlignAllTop -- align interface elements using NSLayoutAttributeTop.
  • .AlignAllBottom -- align interface elements using NSLayoutAttributeBottom.
  • .AlignAllBaseline -- align interface elements using NSLayoutAttributeBaseline.

You can find the complete list in the documentation.

Note: At least one of the elements must have enough defined perpendicular constraints for layout options to work. See the example below:

  NSLayoutConstraints.constraintsWithVisualFormat(
    "V:[topView]-[middleView]-[bottomView]",
    options: [.AlignAllLeading],
    metrics: nil,
    views: ["topView": topView, "middleView": middleView, "bottomView": bottomView"])

The topView, middleView or bottomView must have constraints defining the position of their leading edge for Auto Layout to generate the correct constraints.

And now for a new concept! Meet Metrics.

Metrics

Metrics are a dictionary of number values that can appear inside the VFL format string. These are particularly useful if you have standardized spacing or calculated size values that you can't type directly into the format string.

Add the following constant declaration above your variable declarations in ViewController.swift:

// MARK: - Constants
private let horizontalPadding: CGFloat = 15.0

Now that you have a constant for the padding, you can create a metrics dictionary and utilize the constant. Add the following code above your views declaration in viewDidLoad():

let metrics = ["hp": horizontalPadding,
  "iconImageViewWidth": 30.0]

The above code creates a dictionary of key / value pairs to be substituted into the format string.

Next, replace the topRowHorizontalConstraints and summaryHorizontalConstraints definitions with the following:

let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-hp-[iconImageView(iconImageViewWidth)]-[appNameLabel]-[skipButton]-hp-|",
  options: [.AlignAllCenterY],
  metrics: metrics,
  views: views)

let summaryHorizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "H:|-hp-[summaryLabel]-hp-|",
  options: [],
  metrics: metrics,
  views: views)

You're replacing the hard coded values in the format string with placeholders that represent keys from the metrics dictionary. You also set the metrics parameter to the metrics dictionary.

Auto Layout will perform string substitution, replacing the placeholder text with the value inside the metrics dictionary. Lastly, in the above case, hp will be replaced with the constant 15 points, and iconImageViewWidth will be replaced with the constant 30 points.

You've removed a repeatedly used magic number and replaced it with a nice clean variable. If you decide to change the padding, you only have to change one thing. Isn't that better? The metrics dictionary isn't limited to constants either; if you need to calculate things at run time and put them in the dictionary, that's fine too.

The final piece of the puzzle to place is how you lay out interface elements when your view controllers are embedded inside a UINavigationController or UITabBarController.

Layout Guides

View controllers have two available layout guides:

  • topLayoutGuide
  • bottomLayoutGuide

Both indicate the location of the top or bottom bar edges in a view controller’s view, but currently In Grapevine, the only bar edges being displayed are from the status bar.

Update the iconVerticalConstraints declaration to the following:

let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:|-[iconImageView(30)]",
  options: [],
  metrics: nil,
  views: views)

Here you remove the 20 points of spacing from the top edge of the iconImageView to the top edge of its superview. Build and run your project:

Grapevine-Without-20pts

Now the status bar covers your top interface elements. Also, in landscape mode, the iconImageView is flush with the top of the screen because iOS removes the status bar to provide more real estate for smaller devices.

Playing around with topLayoutGuide will fix this problem. Replace your views dictionary definition with the following:

  let views: [String: AnyObject] = ["iconImageView": iconImageView,
    "appNameLabel": appNameLabel,
    "skipButton": skipButton,
    "appImageView": appImageView,
    "welcomeLabel": welcomeLabel,
    "summaryLabel": summaryLabel,
    "pageControl": pageControl,
    "topLayoutGuide": topLayoutGuide,
    "bottomLayoutGuide": bottomLayoutGuide]

Here you change the views definition to include type information [String: AnyObject], which is necessary since up until this point you've been putting String's and UIView subclasses into the views dictionary.

With the latest changes, you're adding the topLayoutGuide and bottomLayoutGuide, which inherit from UILayoutSupport and not UIView, into the dictionary.

Next, you need to use the layout guides to align the interface elements. Update the iconVerticalConstraints declaration to the following:

let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
  "V:[topLayoutGuide]-[iconImageView(30)]",
  options: [],
  metrics: nil,
  views: views)

All you're doing here is removing the reference to the superview and aligning the top edge of the iconImageView with the topLayoutGuide of the view controller. Build and run your project!

Grapevine-Final

There you go! Now your top interface elements are laid out against the topLayoutGuide and the status bar's display preference controls the layout changes in both portrait and landscape mode.

In this section, you've seen usage of the topLayoutGuide help manage your interface elements' layout when there is a status bar. If your view controller was embedded inside a UINavigationController, then the topLayoutGuide would take into account the status bar and also the UINavigationBar. However, if the controller was embedded inside a UITabBarController, then the bottomLayoutGuide would come into play, ultimately determining the bottom edges of your controller's view.

Limitations

VFL makes it possible to write multiple constraints using just one line of code, reducing the burden on your fingertips. However, there are some limitations to the current implementation; a couple of the more notable are important to understand:

  • Centering of views
  • Using the multiplier component of constraints

Centering of Views

Within Grapevine, you've centered views using the layout options .AlignAllCenterY and .AlignAllCenterX.

Using these means you aligned views to other views respective to horizontal and vertical centers, however this only works if one of the views you're aligning already has enough constraints to describe its horizontal or vertical centers.

While there are tricks you can use to center views using the VFL, there are no guarantees that they'll work in future versions.

constraints_constraining

Using the Multiplier Component of Constraints

With this, you have the ability to set fixed aspect ratios on views or to do something like make a label take up only 60 percent of its superview's width. Since the VFL creates multiple constraints and returns only an array of un-named constraints, the multiplier cannot be set through the format string.

Note: You could loop through each of the constraints returned by the constraintsWithVisualFormat method, but you would have to process each of them in turn to determine the NSLayoutAttribute so that you could correctly set your multiplier. But even then, you still have to replace that constraint because the multiplier isn't mutable.

Where To Go From Here?

You can download the finished project here.

Note: Sometimes Xcode has problems when several projects share the same bundle identifier. So, if you've worked through the tutorial and try to run the downloaded final project, you might need to clean the build folder by pressing option and selecting Product \ Clean Build Folder.

Now that you know how the Visual Format Language works, you’re ready to take this knowledge and layout your own interfaces.

You've seen how to use layout options to reduce the number of constraints you have to define. You've seen how metrics can be defined not only at compile time, but also at runtime. Lastly, you've seen that there are limitations to the Visual Format Language, but it has more pros than cons and you should take advantage of it where appropriate.

In the meantime, if you have any questions or comments about this tutorial or Auto Layout in general, please join the forum discussion below!

Darren Ferguson

Software Developer originally from the U.K. but now residing just outside of Washington D.C. in Northern Virginia. Currently working as an app developer specializing in iOS for M.C. Dean, Inc, a systems integration provider based out of Northern Virginia.

When not coding you will find me enjoying EPL Football, spending time with my family and traveling as much as possible

Other Items of Interest

Save time.
Learn more with our video courses.

raywenderlich.com Weekly

Sign up to receive the latest tutorials from raywenderlich.com each week, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

PragmaConf 2016 Come check out Alt U

Our Books

Our Team

Video Team

... 20 total!

Swift Team

... 15 total!

iOS Team

... 42 total!

Android Team

... 16 total!

macOS Team

... 11 total!

Unity Team

... 11 total!

Articles Team

... 12 total!

Resident Authors Team

... 15 total!