Swift Components Tour – Autolayout Intro – Where? pt. 2

In this lesson

The Swift Components Tour is over! But let’s talk about autolayout, specifically the who, what, when, where, why, and how of autolayout. Today, where to use autolayout, part 2, interface builder.

Kyle Roberts
Swift Guru at Large

Kyle's Series


Tap on time to skip ahead


Just to restate, this video is the Why? Of Autolayout. It is not the How? We’re going to get a little bit ahead of ourselves and you’re going to see some Autolayout in action. Most of the explanation of what I’m doing is going to be saved for another video.


Here we have Button1 and Button2 placed next to each other using a frame based layout because we haven’t set any constraints yet. These buttons don’t have any borders because we’re now in iOS 8 and the styles have changed since that example was written, I guess. To place Button1 12 pixels to the left of Button2, we are going to want to set some constraints to center this Button2 in the screen just so it knows where it’s supposed to be placed. Then we can place Button1 using Button2 as a reference, 12 pixels to the left.


We’ll right click drag from Button2 to Button1 and select horizontal spacing. Then, just so that Button1 has the correct Y value, we’re also going to center the Y of Button1 with the center Y of Button2. To make sure they are 12 pixels apart, we can select this constraint here, which is matching the left side of Button2 to the right side of Button1. You’ll see that the constant of this is 76, which it just gathered from the current context of the two buttons. We know that’s not what we want. We are going to set this to 12 pixels. And boom. It’s going to move Button1 12 pixels to the left of Button2.


Once you know how to do that you can fly through this laying out huge amounts of views on a screen that will look good on any canvas, assuming the canvas is big enough for your content, without writing any code, especially worrying about visual format language and double especially avoiding that seven line method. It just takes a lot of time to visualize in your head while you’re writing it. Otherwise, Interface Builder does all that visualizing for you and you just have to click and drag a few times, change a few values. That’s about as simple as it gets.


I hope you know see why I choose to use Autolayout over frame based layouts and why it is much easier to use Autolayout in Interface Builder than in code. At least without any third party libraries. But I would still say that using Autolayout in Interface Builder is easier than that. Thanks for watching.

Additional Info

Register to get access to additional resources and info.