TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to create Auto Layout constraints in code: constraints(withVisualFormat:)

Swift version: 5.10

Paul Hudson    @twostraws   

While the complexities of Auto Layout make it something most people prefer to grapple with using Interface Builder, it does have some cool tricks up its sleeve if you prefer to work in code. One of those tricks is called Visual Format Language (VFL) and lets you use ASCII art to tell iOS how you want your views laid out.

First, here's a dummy test case you can copy and paste into your project. It creates five labels of different colors and adds them all to your view:

override func viewDidLoad() {
    super.viewDidLoad()

    let label1 = UILabel()
    label1.translatesAutoresizingMaskIntoConstraints = false
    label1.backgroundColor = UIColor.red
    label1.text = "THESE"
    label1.sizeToFit()

    let label2 = UILabel()
    label2.translatesAutoresizingMaskIntoConstraints = false
    label2.backgroundColor = UIColor.cyan
    label2.text = "ARE"
    label2.sizeToFit()

    let label3 = UILabel()
    label3.translatesAutoresizingMaskIntoConstraints = false
    label3.backgroundColor = UIColor.yellow
    label3.text = "SOME"
    label3.sizeToFit()

    let label4 = UILabel()
    label4.translatesAutoresizingMaskIntoConstraints = false
    label4.backgroundColor = UIColor.green
    label4.text = "AWESOME"
    label4.sizeToFit()

    let label5 = UILabel()
    label5.translatesAutoresizingMaskIntoConstraints = false
    label5.backgroundColor = UIColor.orange
    label5.text = "LABELS"
    label5.sizeToFit()

    view.addSubview(label1)
    view.addSubview(label2)
    view.addSubview(label3)
    view.addSubview(label4)
    view.addSubview(label5)
}

If you run the project, you'll see the labels are all bunched up in the top-left corner, which doesn't look great. To fix this, we're going to use VFL to have each label occupy the full width of the screen, then spaced out so they are position below each other.

When you use VFL you need to create a dictionary of the views you want to work with. This dictionary needs to have the name of the view inside VFL and a reference to the view itself, but in practice most people just use the same name for VFL as the variable like this:

let viewsDictionary = ["label1": label1, "label2": label2, "label3": label3, "label4": label4, "label5": label5]

Put that just below the final addSubview() call.

Now for the VFL itself: put this directly beneath the previous line in order to have every label stretch out to occupy the full width of the screen:

for label in viewsDictionary.keys {
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[\(label)]|", options: [], metrics: nil, views: viewsDictionary))
}

Finally, add this to make the views lay themselves out below each other:

view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[label1]-[label2]-[label3]-[label4]-[label5]", options: [], metrics: nil, views: viewsDictionary))

This is only the beginning of what VFL can do – you should definitely read my Auto Layout tutorial for more details.

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 6.0 – see Hacking with Swift tutorial 6

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.