Basic VFL Constraints

Among the many ways to use Auto Layout in iOS development – Apple’s Visual Formatting Language is one of the more difficult concepts I’ve had to get my head around. I thought I would write down some simple swift examples to get you started if you’ve just joined the party.

What is it?

The Visual Formatting Language or VFL is a tool that lets us create auto layout constraints with strings that contain layout instructions or ‘Grammar’. For example, the following VFL string defines the horizontal constraints on a UIView, the view will be pinned to the left and right of it’s super view with 10px padding.

"H:|-10-[view]-10-|"

Setup

Firstly ensure that any objects you want to add constraints to have been added to your super view and they have setTranslatesAutoresizingMaskIntoConstraints set to false

var viewObject = UIView()
viewObject.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubView(viewObject)

To use VFL with our objects we need a way of assigning each object a name that can be used in the VFL string, the way to do this is to make a simple dictionary as below.

var viewDict = ["view":viewObject]

The same goes for adding any padding, if we want computed values we set these up in a dictionary.

var metricDict = ["padding":10]

Now we can construct our VFL strings, you need one for each ‘direction’ or ‘column’ Horizontal and Vertical constraints.

var horizontal = "H:|-(padding)-[view]-(padding)-|"
var vertical = "V:|-(padding)-[view]-(padding)-|"

The last step is to create the NSLayoutConstraints and add them to your viewObject’s super view.

var hConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontal, options: nil, metrics: metricDict, views: viewDict)
var vConstraints = NSLayoutConstraint.constraintsWithVisualFormat(vertical, options: nil, metrics: metricDict, views: viewDict)
self.view.addConstraints(hConstraints)
self.view.addConstraints(vConstraints)

Result

The result of all this is a pretty basic view with 10px padding the whole way around the screen, however coding layouts in this way means that much more complex layouts can be achieved with far less code.

To read more about VFL layouts, syntax and a whole list of Grammar that can be used within VFL strings, checkout Apple’s documentation at the link below.