Beginning Auto Layout in iOS 6: Part 2/2

Update note: Check out our newer version of this tutorial, updated to Swift and iOS 8: Beginning Auto Layout Tutorial in Swift: Part 2. This tutorial is an abbreviated version of one of the chapters from our new book iOS 6 By Tutorials. Matthijs Hollemans wrote this – the same guy who wrote the iOS […] By Matthijs Hollemans.

Login to leave a rating/review
Save for later

Learn Auto Layout in the iOS 6 SDK!

Update note: Check out our newer version of this tutorial, updated to Swift and iOS 8: Beginning Auto Layout Tutorial in Swift: Part 2.

This tutorial is an abbreviated version of one of the chapters from our new book iOS 6 By Tutorials. Matthijs Hollemans wrote this – the same guy who wrote the iOS Apprentice Series. Enjoy!

In part 1 of this tutorial you saw that the old “struts-and-springs” model for making user interfaces cannot easily solve all layout problems. The new Auto Layout feature from iOS 6 is the solution, but because this technology is so powerful it is also a bit more tricky to use.

In this second part and final part of the tutorial series, you’ll continue learning all about constraints and how to apply them!

As bold as a user constraint

Maybe you noticed that some of the T-bars in the canvas are thicker than others. The bold ones are called user constraints, and unlike the thin ones you can delete them. However, when you delete a user constraint, Interface Builder will often put a non-deletable constraint in its place. You will soon see why.

In the Document Outline, user constraints have a blue icon:

User constraints document outline

Select the Vertical Space (40) constraint and tap the Delete key on your keyboard. The T-bar between the two buttons disappears and is replaced by a new Vertical Space constraint that goes all the way to the bottom:

After deleting user constraint

This new constraint has a purple icon and does not have a bold line, meaning that you cannot delete this one. The two buttons are no longer connected vertically, although they are still left-aligned due to the Leading Alignment constraint.

Why does this happen? Why does Interface Builder attach a new Vertical Constraint to the button, even though you just told it to delete such a constraint? The answer is this:

For each view there must always be enough constraints to determine both its position and size.

That is the most important rule to remember when it comes to using Auto Layout. If there aren’t enough constraints, then Auto Layout will be unable to calculate where your views should be positioned or how big they should be. Such a layout is considered to be invalid. You will see examples of such invalid layouts later on.

Interface Builder tries very hard to prevent you from making layouts that are invalid. The size of these two buttons is known because buttons know how big they should be, based on their text, background image, and so on – intrinsic content size, remember? So that’s not a problem. The X-position of the top button is also known because its left edge is aligned with the bottom button, and the bottom button is always horizontally centered. The only unknown is the Y-position.

Previously, the two buttons were connected with a Vertical Space. That was enough to determine the Y-position of the top button. But if you delete that Vertical Space, then the top button has nothing to anchor it vertically in the view. It cannot just float there because then Auto Layout has no way to determine what its Y-coordinate should be.

To prevent this from happening, Interface Builder needs to “pin” the button somewhere and the bottom edge is closest.

Pin all the buttons

Funnily enough, if you run the app and flip to landscape, it still seems to work. The screen looks exactly the same as it did before. That is true, but your design is fundamentally different: both buttons are now connected to the bottom of the window. This means that if the bottom button moves, the top one doesn’t move with it. (Note that either solution is fine, it just depends on what you want your app to do. But in this example, you want to have a vertical connection between the two buttons.)

To illustrate this, select the Vertical Space constraint between the lower button and the screen’s edge. Go into the Attributes inspector. It’s Constant should currently read “Auto”, and Standard is checked because this is a standard margin space. Change it to 40.

Because the buttons are not connected, only the lower button moves upward; the top button stays put:

Only bottom button moves up

Notice that changing the Constant value of the constraint promoted it to a bold “user” constraint.

Needles and pins

Let’s connect the two buttons again. So far you have made constraints by dragging the buttons on the canvas, but you can also make them afterwards. Hold down the Cmd key and click both buttons to select them. From the Editor menu, choose Pin\Vertical Spacing.

You can also use the little panel in the bottom-right corner to make this constraint:

Shortcut menu pin

It pops up the following menu:

Pin menu

Regardless of the method you choose, this adds a new constraint between the two buttons:

Pin vertical spacing

The new constraint is a Vertical Space constraint with a Constant of 20 points. That is because the distance between the two buttons was 20 points at the time you made this connection.

Notice that the old Vertical Space from the upper-most button to the bottom edge is still there. This constraint – the one that says Vertical Space (104) – is no longer needed, so delete it.

Previously when you deleted a blue constraint, a purple one took its place. Now that does not happen, because the remaining constraints are sufficient to position all the views. Interface Builder only adds new constraints when the existing ones are no longer adequate.

You should now have the following constraints:

Restored constraints

Select the bottom Vertical Space (by clicking on the canvas) and change its Constant from 40 back to Standard. This should not only move the bottom button downwards, but the top button as well, because they are connected again.

A little runtime excursion

You’ve seen a bit of the basics now: you know how to place controls using the guides, how to align them relative to one another, and how to put space between controls. Over the course of this tutorial you will also use the other options from the Align and Pin menus.

Playing with this in Interface Builder is all well and good, but let’s see how this works at runtime. Add the following method to ViewController.m:

- (IBAction)buttonTapped:(UIButton *)sender
    if ([[sender titleForState:UIControlStateNormal] isEqualToString:@"X"])
        [sender setTitle:@"A very long title for this button" 
        [sender setTitle:@"X" forState:UIControlStateNormal];

This simply toggles between a long title and a short title for the button that triggered the event. Connect this action method to both of the buttons in Interface Builder: Ctrl-drag from each button to File’s Owner and select buttonTapped: in the popup.

Run the app and tap the buttons to see how it behaves. Perform the test in both portrait and landscape orientations.

Long and short titles

Regardless of which button has the long title and which has the short title, the layout always satisfies the constraints you have given it:

  • The lower button is always center-aligned in the window, horizontally.
  • The lower button always sits 20 points from the bottom of the window.
  • The top button is always left-aligned with the lower button.

That is the entire specification for your user interface.

For fun, select both buttons in Interface Builder and from the Align menu pick Right Edges. Now run the app again and notice the differences.

Repeat, but now choose Align\Horizontal Centers. That will always center the top button with respect to the bottom button. Run the app and see how the buttons act when you tap them.

Fixing the width

The Pin menu has an option for Widths Equally. If you set this constraint on two views, then Auto Layout will always make both views equally wide, based on which one is the largest. Let’s play with that for a minute.

Select both buttons and choose Pin\Widths Equally. This adds a new constraint to both buttons:

Buttons widths equally

Note: If you get an extra unintended constraint between one of the buttons and the superview, select the two buttons and select Align\Horizontal Centers again.

You have seen this type of constraint before, in the first part of this tutorial. It looks like the usual T-bar but in the middle it has a circle with an equal sign.

In the Document Outline this shows up as a single Equal Widths constraint:

Equal widths in document outline

Changing the label text on one button will now change the size of the other one as well.

Change the bottom button’s label to “X”, just to make it really small. You will notice that the top button no longer fits its text:

Top button text no longer fits

So how does Interface Builder know which button’s size to use for both of them? If you pay close attention, you’ll see that a Width constraint was added to the button with the truncated text:

Width constraint on truncated button in document outline

Width constraint on truncated button

Interface Builder does this to force the button to become smaller than what it would ideally be, in order to comply with the Equal Widths constraint.

Obviously this is not what you want, so select the top button and choose Size to Fit Content from the Editor menu (or press Cmd =). Now the text fits inside the button again – or rather, the button fits around the text – and the Width constraint is gone.

Run the app and tap the buttons. The buttons always have the same width, regardless of which one has the largest label:

Buttons equal widths in app

Of course, when both labels are very short, both buttons will shrink equally. After all, unless there is a constraint that prevents, buttons will size themselves to fit their content exactly, no more, no less. What was that called again? Right, the intrinsic content size.

Intrinsic Content Size

Before Auto Layout, you always had to tell buttons and other controls how big they should be, either by setting their frame or bounds properties or by resizing them in Interface Builder. But it turns out that most controls are perfectly capable of determining how much space they need, based on their content.

A label knows how wide and tall it is because it knows the length of the text that has been set on it, as well as the font size for that text. Likewise for a button, which might combine the text with a background image and some padding for the rounded corners.

The same is true for segmented controls, progress bars, and most other controls, although some may only have a predetermined height but an unknown width.

This is known as the intrinsic content size, and it is an important concept in Auto Layout. You have already seen it in action with the buttons. Auto Layout asks your controls how big they need to be and lays out the screen based on that information.

You can prevent this by setting an explicit Width or Height constraint on a control. If you resize the control by hand, then Interface Builder will set such an explicit constraint for you. With the Size to Fit Content command, you remove any fixed Width or Height constraints and let the control determine its intrinsic content size again.

Usually you want to use the intrinsic content size, but there are some cases where you may not want to do that. Imagine what happens when you set an image on a UIImageView if that image is much larger than the screen. You usually want to give image views a fixed width and height and scale the content, unless you want the view to resize to the dimensions of the image.

So what happens when one of the buttons has a fixed Width constraint on it? Buttons calculate their own size, but you can override this by giving them a fixed width. Select the top button and choose Pin\Width from the menu. This adds a solid T-bar below the button:

Button fixed width constraint

Because this sort of constraint only applies to the button itself, not to its superview, it is listed in the Document Outline below the button object. In this case, you have fixed the button to a width of 73 points.

Run the app and tap the buttons. What happens? The button text does change, but it gets truncated because there is not enough room:

Button text clipped

Because the top button has a fixed-width constraint and both buttons are required to be the same size, they will never shrink or grow.

Note: You probably wouldn’t set a Width constraint on a button by design – it is best to let the button use its intrinsic size – but if you ever run into a layout problem where you expect your controls to change size and they don’t, then double check to make sure Interface Builder didn’t sneak a fixed Width constraint in there.

Play around with this stuff for a bit to get the hang of pinning and aligning views. Get a feel for it, because not everything is immediately obvious. Just remember that there must always be enough constraints so that Auto Layout can determine the position and size for all views.

Got enough constraints

Gallery example

You should now have an idea of what constraints are and how you can build up your layouts by forging relationships between the different views. In the following sections, you will see how to use Auto Layout and constraints to create layouts that meet real-world scenarios.

Let’s pretend you want to make an app that has a gallery of your favorite programmers. It looks like this in portrait and landscape:

The Gallery app

The screen is divided into four equal quarters. Each quarter has an image view and a label. How would you approach this?

Let’s start by setting up the basic app. You can use your existing “Constraints” app by deleting the buttons and reusing the view.

Or, you can create a new project using the Single View Application template and name it as you like, for instance, “Gallery”. This will just use a nib, so disable the storyboards option.

Open ViewController.xib. From the Object Library, drag a plain view object onto the canvas. Resize the view so that it is 160 by 230 points, and change its background color to be something other than white (I made mine green):

View with auto layout

This view has four constraints to keep it in place. Unlike a button or label, a plain UIView does not have an intrinsic content size. There must always be enough constraints to determine the position and size of each view, so this view also needs constraints to tell it what size it needs to be.

You may wonder, where are these size constraints? In this case, the size of the view is implied by the size of the superview. The constraints in this layout are two Horizontal Spaces and two Vertical Spaces, and these all have fixed lengths. You can see this in the Document Outline:

Constraints for UIView in document outline

The width of the green view is calculated by the formula “width of superview minus (109 + 51)” and its height by the formula “height of superview minus (153 + 77)”. The space constraints are fixed, so the view has no choice but to resize. When you rotate the app, the dimensions of the superview change from 320×460 to 480×300. Plug this new width and height into these formulas, and you’ll get the new size of the green view.

You can see this for yourself when you run the app and flip to landscape, but you can also simulate it directly in Interface Builder.

Select the top-most view in the nib and go to the Attributes inspector. Under the Simulated Metrics section, change Orientation to Landscape:

Simulated metrics landscape

This gives you an instant preview of what the nib’s layout will look like in landscape orientation. The green view has resized in order to satisfy its Horizontal and Vertical Space constraints.

Switch back to portrait orientation.

Note: There are two main reasons why you would drop a plain UIView onto a nib: a) You’re going to use it as a container for other views, which helps with organizing the content of your nibs; or b) It is a placeholder for a custom view or control, and you will also set its Class attribute to the name of your own UIView or UIControl subclass.

You may not always want your UIView to resize when the device rotates, so you can use constraints to give the view a fixed width and/or height. Let’s do that now. Select the green view and from the Pin menu, choose Width. Select the view again and choose Pin\Height.

You have now added two new constraints to the view, a 160 point Width constraint and a 230 point Height constraint:

Width and height constraints on UIView

Because Width and Height apply to just this view, they are located in the Document Outline under the View itself. Usually, constraints express a relationship between two different views – for example, the Horizontal and Vertical Space constraints are between the green view and its gray superview – but you can consider the Width and Height constraints to be a relationship between the view and itself.

Run the app. Yup, looks good in portrait. Now flip over to landscape. Whoops! Not only does it not look like you wanted – the view has changed size again – but the Xcode debug pane has dumped a nasty error message:

Gallery[68932:11303] Unable to simultaneously satisfy constraints.
	Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
    "<NSLayoutConstraint:0x754dac0 V:[UIView:0x754e510(230)]>",
    "<NSLayoutConstraint:0x754eac0 V:|-(77)-[UIView:0x754e510]   (Names: '|':UIView:0x754e3a0 )>",
    "<NSLayoutConstraint:0x754ea40 V:[UIView:0x754e510]-(153)-|   (Names: '|':UIView:0x754e3a0 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7558cd0 h=-&- v=-&- UIView:0x754e3a0.width == UIWindow:0x71156e0.width - 20>",
    "<NSAutoresizingMaskLayoutConstraint:0x74128b0 h=--- v=--- H:[UIWindow:0x71156e0(320)]>"

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x754dac0 V:[UIView:0x754e510(230)]>

Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Remember when I said that there must be enough constraints so that Auto Layout can calculate the positions and sizes of all the views? Well, this is an example where there are too many constraints. Whenever you get the error “Unable to simultaneously satisfy constraints”, it means that your constraints are conflicting somewhere.

Let’s look at those constraints again:

Conflicting constraints

There are six constraints set on the green view, the four Spacing constraints you saw earlier and the new Width and Height constraints that you have just set on it. So where is the conflict?

Well, in portrait mode there shouldn’t be a problem because the math adds up. The width of the superview is 320 points. If you add the lengths of the Horizontal Space constraints and the Width of the view, then you should also end up at 320. The way I have positioned the view, that is: 51 + 160 + 109 = 320 indeed. Likewise, the vertical constraints should add up to 460.

But when you rotate the device to landscape, the window (and therefore the superview) is 480 points wide. That means 51 + 160 + 109 + ? = 480. There are 160 extra points that need to go somewhere in that equation and Auto Layout doesn’t know where to get them. Likewise for the vertical axis.

The conflict here is that either the width of the view is fixed and one of the margins must be flexible, or the margins are fixed and the width must be flexible. So one of these constraints has to go. In the above example, you want the view to have the same width in both portrait and landscape, so the trailing Horizontal Space has got to go.

Remove the Horizontal Space at the right and the Vertical Space at the bottom. The nib should look like this:

Conflicting constraints fixed

Now the view has just the right number of constraints to determine its size and position, no more, no less. Run the app and verify that the error message is gone and that the view stays the same size after rotating.

Note: Even though Interface Builder does its best to prevent you from making invalid layouts, it cannot perform miracles. At least Auto Layout spits out a detailed error message when something is wrong. You will learn more about analyzing these error messages and diagnosing layout problems in “Intermediate Auto Layout” in iOS 6 by Tutorials.

Painting the portraits

Drag a label onto the green view. Notice that now the guides appear within that green view, because it will be the superview for the label.

Drag label into green view

Position the label in the top-left corner against the guides. This will add two Space constraints to anchor the label in the top-left corner of the green view:

Label constraints

Notice that these two new Horizontal and Vertical Space constraints are listed under the green view’s Constraints section, not in the main view.

Now move the green view around a bit. You’ll see that only the constraints between the green view and its superview change, but those for the label don’t. The label always stays put in the same place, relative to the green view.

Select the label and place it against the bottom margin, horizontally centered. Then drag a new image view object on to the nib, and make the layout look like this:

Image view in gallery

The image view is pinned to the top, left and right edges of its superview, but its bottom is connected to the top of the label with a standard spacing.

Download the resources for this tutorial and unzip the file. You will find an Images folder – add this folder into your project. Set Ray.png as the image for the image view, change the image view’s mode to Aspect Fit and set its background color to white. Change the label’s text to say “Ray”.

Your layout should now look like this:

Gallery with Ray

Notice that Interface Builder has placed a Height constraint on the label now. This happened the moment you set the image on the image view.

Label fixed height

Interface Builder tries to prevent what are known as ambiguous layouts. If neither the image view nor the label has a fixed height, then Auto Layout doesn’t know by how much to scale each if the height of the green view should change. (Interface Builder seems to ignore for now that the green view actually has a fixed Height constraint set on it.)

Let’s say at some point in your app the green view becomes 100 points taller. How should Auto Layout distribute these new 100 points among the label and the image view? Does the image view become 100 points taller while the label stays the same size? Or does the label become taller while the image view stays the same? Do they both get 50 points extra, or is it split 25/75, 40/60, or in some other possible combination?

Auto Layout is not going to guess, so Interface Builder “fixes” this problem for us by giving the label a fixed height. It could also have given the image view a fixed height, but the label makes more sense.

For now, let’s just live with the Height constraint on the label.

Note: The proper solution to this small layout problem is to change the “Content Compression Resistance Priority” of the label. You will learn more about that later on. If you can’t wait, then go into the Size inspector for the label and set the vertical Content Compression Resistance Priority to 751. The Height constraint on the label should now disappear.

Adding the other heads

Move the green view onto the main view’s top-left corner. Recall that the green view had Horizontal Space and Vertical Space constraints that determined its position in the parent view. It still has those, but they are now set to a value of 0 – they are represented by the thick blue lines (with white borders) at the top and left edges of the window:

View in top-left corner

So even though the view sits completely in the corner, it still needs constraints to anchor it there. Think of these as margins with a value of 0.

Select the green view and tap Cmd-D to duplicate it. Move the duplicate into the top-right corner:

Green view in top-right corner

Duplicate two more times and put these copies in the bottom-left and bottom-right corners, respectively.

Change the screen design to the following:

Gallery design

Those are some good-looking programmers! :-)

Run the app. It looks good in portrait, but not so much in landscape:

Gallery looks bad in landscape

It should be pretty obvious what went wrong: you’ve set a fixed width and height on the four brightly-colored container views, so they will always have those sizes, regardless of the size of their superview.

Select the Width (160) and Height (230) constraints from all four views and delete them. If you run the app now, you’ll get something like this. Also not very good:

Still looks bad in landscape

This looks very much like the problem we solved in the introduction, so if you think back to how we solved that, you’ll recall that we gave the views equal widths and heights.

Select all four colored views and choose Pin\Widths Equally. Select the views again and choose Pin\Heights Equally.

Run the app again and rotate the device. Hmm… it still looks exactly the same as before. Why?

Well, if you look at the screenshot you’ll see that all the views do have the same height, and they also appear to have the same width (the green and brown views are partially obscured by the yellow and blue ones), so our constraints are being met. It’s just not the width and height that you want them to have. There must be other constraints that are getting in the way.

Sure enough, if you look at the constraints on these views, you’ll see that they also have Horizontal and Vertical Space constraints that force them into place (look at list of constraints on the main view, not the four subviews):

Bad H-space

What’s worse, you can’t even delete that constraint. Its T-bar is not bold and the constraint is not blue, so Interface Builder put it there in order to prevent a layout problem.

So why does it do that? Just saying that all four views must have equal sizes is not enough to determine what those sizes should actually be, because Auto Layout does not know how these four views are connected to each other. They appear side-by-side in the design, but there are no actual constraints between them. Auto Layout does not know that it needs to split the window width between the “Ray” and “Matthijs” boxes.

If Auto Layout can’t figure this out by itself, you have to tell it.

To be related

Select the Ray and Matthijs boxes and choose Pin\Horizontal Spacing. Because the boxes are side-by-side, this adds a Horizontal Space constraint with size 0 between them, and that is enough to let Auto Layout know how these two views are related.

Important: Interface Builder does not automatically remove the leading Horizontal Space between the superview and the yellow box (the one from the screenshot above), but it did promote it to a user constraint (a fat bar). You can now delete this space. If you don’t, you will get an “Unable to simultaneously satisfy constraints” error during runtime when you flip to landscape.

Run the app. It should now look like this:

Landscape a bit better

That looks a bit better already. The four boxes now have equal widths, but the heights are still wrong. The solution is similar: put a Vertical Space between the Ray and Dennis Ritchie boxes and remove the Vertical Space between the Dennis Ritchie box and the top of the window.

Run the app again, and this time it looks all right:

Gallery landscape OK

Notice that the “Dennis Ritchie” label is not centered below its image view. This originally happened to me when I typed that text into the label. The label was initially centered in the view, but Interface Builder decided it knew better and replaced that centering constraint with a Horizontal Space. If this happened to you, too, then select that label and choose Align\Horizontal Center in Container to fix it.

A quick note on the image views: they stretch out because you have not given them a fixed size. You may not know it, but that’s intentional on your part. ☺ The image views wouldn’t fit in landscape mode otherwise. However, if you want an image view to keep its original aspect ratio, then you’re out of luck. You cannot achieve the following effect using Interface Builder:

Aspect ratio on images

Unfortunately, Interface Builder does not currently provide a way to make constraints that keep the aspect ratio of a view intact. To do that, you need to create and set the constraints programmatically. You will learn how to do that in “Intermediate Auto Layout” in iOS 6 by Tutorials.

Tip: You have seen that you can preview what the UI will look like in landscape by changing the Orientation setting under Simulated Metrics. You can also test the resizing behavior of your views directly in Interface Builder.

Select the main view. Under Simulated Metrics, set Size to Freeform. This adds resize handles around your nib that you can use to mold it into any shape you want. Auto Layout will recalculate the layout on-the-fly:


However, be careful with this. Sometimes Interface Builder will insert new constraints of its own when you’re resizing, as it did here in the bottom-right corner (it added a Horizontal Space). It may also delete existing constraints when they fall outside of the nib bounds.

Where To Go From Here?

If you’ve made it this far, congratulations – you now know what Auto Layout is all about, and have experimented with the basics! But there’s a lot left to learn…

The tutorial you have just read is only the first half of the Beginning Auto Layout chapter from the book iOS 6 by Tutorials. The second half teaches how to use Auto Layout to create more “real-world” screen layouts, and everything else you need to know about using Auto Layout from Interface Builder.

But like any visual design tool, Interface Builder has its limitations and sometimes it just makes more sense to work with the NSLayoutConstraint objects directly from code. iOS 6 by Tutorials dedicates an entire chapter to this topic, Intermediate Auto Layout. So if you want to get to the bottom of Auto Layout, get the book!


Over 300 content creators. Join our team.