Auto Layout Tutorial in iOS: Getting Started

In this Auto Layout tutorial, you’ll learn how to use constraints and apply them to making iOS apps. By Naeem Shaikh.

Login to leave a rating/review
Download materials
Save for later

In this Auto Layout tutorial, you’ll learn how to use constraints and apply them to making iOS apps.

Update note: Naeem Shaikh updated this tutorial for iOS 12, Xcode 10 and Swift 4.2. Ryan Ackermann wrote the original.

Making apps that look good in any orientation across multiple devices can be a challenge. If you’ve experienced this kind of frustration, despair no longer! Auto Layout makes it easy to support different screen sizes in your apps. In this Auto Layout tutorial, you’ll learn all about constraints and how to apply them.

Note: Auto Layout makes internationalization easy, too. You no longer have to make new XIBs or storyboards for every language you wish to support, including right-to-left languages such as Hebrew or Arabic.

For new iOS developers, here’s a quick overview of Auto Layout:

At first, Apple made one screen size for the iPhone. Developers didn’t have to create flexible interfaces as they only had to fit that one size. Today, differently sized devices and more emphasis on landscape mode demand user interfaces of different sizes. Auto Layout is Apple’s solution to this problem, enabling UI elements to grow, shrink and move depending on screen size.

Later in the tutorial, you’ll work on a project called Gallery Kit. To access the materials you’ll need, click the Download Materials button at the top or bottom of the tutorial. Before you get into the project, it’s important to get acquainted with Auto Layout.

Getting Oriented to Auto Layout

Before creating a user interface, take a tour of Xcode and Interface Builder. Interface Builder is a graphical tool inside Xcode that allows developers to create UIs using Auto Layout. Here are some of the common features you’ll come across when using Interface Builder:

  • The Add New Constraints menu is at the bottom-right of the editor. Use this menu to add new constraints to UI elements like buttons and layout tutorial
  • The Align menu is to left of the Add New Constraints menu. This menu creates alignment constraints. Use this menu to vertically align a label relative to another layout tutorial
  • The Document Outline is on the left side. Use this panel to view the hierarchy of a view’s layout. This is useful when figuring out the relationship of a layout tutorial
  • The Attributes inspector is in the middle utility pane on the right side of Xcode. Use this panel to customize a view’s attributes, such as when changing the background color of a view or the text of a button.
  • T-bars are Xcode’s way of visualizing constraints on a view. In the image below, there are three T-bars representing the button’s top, leading and trailing constraints. These bars also indicate any warnings or errors by turning yellow or red, layout tutorial

A Simple Example

To start learning the ins and outs of Interface Builder, first create an empty iPhone application.

Trivia: When iOS development first started, Interface Builder was a separate and stand-alone application from Xcode!

Open Xcode, select Create a new Xcode project and select the Single View App template.
auto layout tutorial

Enter Buttons for the Product Name. Leave the other options as their defaults and go through the next steps to create the project.

auto layout tutorial

Select Main.storyboard and then View Controller Scene in the Document Outline. Make sure to enable Use Auto Layout, Use Trait Variations and Use Safe Area Layout Guides in the Storyboard’s File inspector:

auto layout tutorial

New from iOS 11: Safe Area Layout Guides let you know the area of your content that is visible underneath anything that navigation or other bars might obscure.

It’s time to get your hands dirty! The best way to get comfortable with Auto Layout is to create a user interface. Ready? Set? Go!

Dynamic Buttons

Click the Library button in the window bar. Find the Button row – it’s easier to search for the word ‘button’ to do this. Drag a button into the white rectangle representing your view controller in the main window area. Drag in a second button and position it below the first.

Now you’ll change the background colors of the buttons. Making sure the inspectors panel is open, click the Attributes inspector and find the Background option in the View section. Give the upper button a green background and the lower button a yellow background.

auto layout tutorial

Select the green button and use the Add New Constraints menu on the bottom-right and enter 40 to make a 40-point constraint to its nearest bottom neighbor. Notice the red I-bar; clicking this will add or remove a constraint in that direction. Select Add 1 Constraint to actually create the constraint for the button. Now select the yellow button and enter 8 to make an 8-point constraint to the bottom of the view controller. Don’t forget to select Add 1 Constraint.

auto layout tutorial

Open the Align menu with the yellow button selected and check Horizontally in Container, then click Add 1 Constraint. Now, select both buttons at the same time using the Shift key and, in the Align menu, check Leading Edges. Again, actually install the constraint by clicking Add 1 Constraint.

auto layout tutorial

You might see a red circle with an arrow in it on the top-left. Usually, this indicates an issue that you need to fix. Don’t worry about this for now. You’ll fix it later. :]

Now you’ll see how this works at runtime. Add the following method to the class in ViewController.swift:

@IBAction func buttonTapped(_ sender: UIButton) {
  if sender.title(for: .normal) == "X" {         
    sender.setTitle("A very long title for this button", for: .normal)
  } else {
    sender.setTitle("X", for: .normal)

This 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. Control-drag from each button to the view controller in the Document Outline and select buttonTapped: in the pop-up.

Build and run the app and tap the buttons to see how they behave. Perform the test in both portrait and landscape orientations.

auto layout tutorial
auto layout tutorial

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

  • The lower button is center-aligned in the window, horizontally.
  • The lower button sits 8 points from the bottom of the window.
  • The top button is 40 points above the lower button and aligned with the lower button.

That is the entire specification for your user interface.

auto layout tutorial

Time to Experiment

For fun, remove the Leading Alignment constraint. To do this, select it in the
Document Outline
and press Delete on your keyboard. Then, select both buttons in Interface Builder and from the Align menu select the Trailing Edges option.

auto layout tutorial

Now run the app again and notice the differences.

auto layout tutorial

Now remove the Trailing Alignment constraint and, with both buttons selected, choose Align ‣ Horizontal Centers. That will center the top button with respect to the bottom button. Run the app and see how the buttons act when you tap them.

auto layout tutorial

Auto Layout Issues: Sometimes Xcode can’t automatically resolve the layout you are trying to define. Most of the time, Xcode hasn’t had a chance to recalculate the view and you’re stuck with an orange box indicating the best guess of where the layout should be. In this case, clicking the Update Frames button should fix the layout tutorial

Sometimes the issue might be trickier to resolve. Select the Resolve Auto Layout Issues button all the way to the right to see a menu of options that can help by updating your existing constraints, adding missing constraints, resetting your constraints to constraints suggested by Xcode or clearing the constraints so that you can start over.

Using Intrinsic Content Size

The Add New Constraints menu has an Equal Widths option. If you set this constraint on two views, Auto Layout will make both views equally wide, based on which is the largest.

Select both buttons and choose Add New Constraints ‣ Equal Widths. This adds a new constraint to both buttons:

auto layout tutorial

Even though there are two T-bars, in the Document Outline this shows up as a single Equal Widths constraint:

auto layout tutorial

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

auto layout tutorial

When both labels are short, the buttons will shrink equally. Unless a constraint prevents it, buttons will size themselves to fit their content. A button or label knows how wide and tall it is because it knows the length and font size of the text it displays or, in the case of a button, a combination of text with a background image and some padding. That’s the intrinsic content size, an important concept in Auto Layout.

You’ve 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. Usually, you want to use the intrinsic content size, but there are some cases where you may not want to do that. In these cases, you can set an explicit width or height constraint on a view.

Play around to get a feel for pinning and aligning views. Remember, you need enough constraints that Auto Layout can determine the position and size for all views.

auto layout tutorial

Putting it Into Practice: Gallery Example

You should now understand constraints and how you can build your layouts by forging relationships between the different views. In the following sections, you’ll see how to use Auto Layout and constraints to create layouts that meet real-world scenarios.

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

auto layout tutorialauto layout tutorial

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

If you haven’t already, download the Gallery Kit project using the Download Materials button at the top or bottom of this tutorial and open the starter project. The sample project includes the images you’ll need to display in the gallery.

Open Main.storyboard and select the iPhone SE size from the View As panel on the bottom-left.

auto layout tutorial

From the Library, drag a plain View object onto the canvas. With the view selected, open the Size inspector and set the Width to 160 and Height to 284 points.

Next, in the Attributes inspector, set the view’s background color to green:

auto layout tutorial

There are two reasons why you would drop a plain UIView onto a storyboard. First, you’re going to use it as a container for other views, which helps with organizing the content of your scenes. Secondly, it’s a placeholder for a custom view or control. In the second case, you’ll also set its Class attribute to the name of your own UIView or UIControl subclass.

Select the green view, open the Add New Constraints menu and uncheck Constrain to margins. Create four constraints to all four of the green view’s nearest neighbors in each direction by clicking the red I-bars:

auto layout tutorial

This will create four new constraints between the green view and its superview, one for each side of the view. The actual spacing values may be different, depending on where you placed the view. You don’t have to change the values to match the ones above. Click Add 4 Constraints to finish.

Your storyboard should now look something like this:

auto layout tutorial

The Safe Area

Are you wondering why the constraint at the top of the view stops at the status bar instead of going all the way up to the top of the screen?

auto layout tutorial

Since iOS 7, the status bar is always on top of the view controller — it’s no longer a separate bar — so what gives? When you created the constraint, it didn’t attach to the top of the screen but the top of an invisible rectangle called the Safe Area.

The Safe Area is the part of the view controller that isn’t obscured by any bars like the status, navigation or tab bar. Because the navigation bar has a different height in landscape, the Safe Area resizes with the bar when the device is rotated. That makes it easy to place views relative to the navigation bar. The same goes for tab bars.

This view needs four constraints to keep it in place. Unlike a button or label, a plain UIView does not have an intrinsic content size. You must add constraints to determine the position and size of each view.

In this case, the size of the view is implied by the size of the superview. This layout has leading, trailing, top and bottom constraints, and these all have fixed lengths. You can see this in the Document Outline:

auto layout tutorial

The width of the green view is calculated by the formula: width of safe area minus (80 + 80); and its height by the formula: height of safe area minus (13 + 163). The constraints are fixed, so the view has no choice but to resize. Again, your values may be different, depending on where you put the view.

When you rotate the app, the dimensions of the superview change, so the view’s size changes with it. Build and run the app, then rotate the simulator to see how the view behaves.

auto layout tutorial
auto layout tutorial

Fixed Sizes

You may not always want your view to resize when the device rotates, so you can use constraints to give the view a fixed width and/or height. Do that now.

Select the green view and click Add New Constraints. In the pop-up, select Width and give it a value of 160; then select Height and specify its value to be 372:

auto layout tutorial

Click Add 2 Constraints to finish. You’ve added two new constraints to the view, a 160-point width constraint and a 372-point height constraint.

Also change the values in the existing constraints by selecting each one from the Document Outline and modifying their values in the Size inspector. Use these values: top: 13, leading: 80, trailing: 80, bottom: 163.

Run the app. Yep, it looks good in portrait.

auto layout tutorial

Now rotate to see it in landscape. Whoops! Not only does it not look like you wanted, but the Xcode debug pane has dumped a nasty error message that looks like this at the top:

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. 
Will attempt to recover by breaking constraint....

Remember when I said 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. When you get the error “Unable to simultaneously satisfy constraints,” it means your constraints are in conflict.

To solve this, remove the Safe Area.trailing = View.trailing at the right and the Safe Area.bottom = View.bottom at the bottom by selecting them in the Document Outline and hitting delete.

The storyboard should look like this:

auto layout tutorial

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

auto layout tutorial
auto layout tutorial

Next, select the green view’s height constraint and, in the Size inspector, change its Constant to 284. This will make sure it’s half as large as the screen.

Painting the Portraits

From the Library, drag a Label onto the green view. Notice that now the guides appear within that green view because it’s the superview for the label.

auto layout tutorial

Position the label against the bottom margin, spaced equally from the guides.

You now need to add a space constraint to anchor the label against the bottom, left and right of the green view, at 20 points distance. Ensuring that the label is selected, click the Add New Constraints button. Enter 20 for each of the bottom, left and right constraints, making sure the I-bar is solid, then select Add 3 Constraints:

auto layout tutorial

Now, in the Attributes inspector, select Center Alignment.

auto layout tutorial

It’s important to have a right and left constraint on UILabels. Otherwise, they will show outside their superview when the text is too long.

Notice that these new constraints are listed under the green view’s own Constraints section, not in the main view.

Adding Images

From the Library, drag a new Image view object onto the storyboard and make the layout look like this:

auto layout tutorial

The image view’s top, left, and right edges are pinned to its superview, but its bottom is connected to the top of the label with a standard spacing of 8 points. If you’re unsure of how to do this, then follow these steps.

1. Drag an Image view from the Library into the green view. Don’t worry about its size or position:

auto layout tutorial

2. With the Image view selected, click Add New Constraints and choose the following options:

auto layout tutorial

The top, left, and right I-bars are set to 20 points, but the bottom one is set to 8 points.

The constraints you chose result in a different frame than the image view’s current position and size. Interface Builder will automatically adjust the frame as it adds the constraints.

Now you’re ready to add images and names to your view. You’ll use the bundled images included in Assets.xcassets.

Still in Main.storyboard, select the Image view and, in the Attributes inspector, set Ray as the Image. Also set the Content Mode to Aspect Fit. Then, set the Background to White Color.

Double click the Label, and set its title to Ray.

Your layout should look like this:

auto layout tutorial


Notice that the constraints inside the green view turned red. This happened the moment you set the image on the image view. Why is your layout invalid? Take the guesswork out of it. Xcode will tell you what’s wrong.

Click the small red arrow next to View Controller Scene in the Document Outline to view the issues:

auto layout tutorial

You have a Content Priority Ambiguity error. That’s a mouthful! Here’s what it means: 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.

Say at some point, 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 some other combination?

If you don’t solve this problem, Auto Layout has to guess, and the results may be unpredictable.

The solution is to change the Content Hugging Priority of the label. You can imagine hugging here to mean size-to-fit. In other words, the bounds of the view will hug the intrinsic content size. A higher value here means the view will be less likely to grow and more likely to stay the same.

Go into the Size inspector for the label and set the Vertical Content Hugging Priority to 252. That makes it one higher than the priority of the image view. As a result, when the superview changes size, the image view will be the one to resize, and the label will stay the same size.

auto layout tutorial

The T-bars should turn blue again and the Auto Layout warnings should have disappeared.

Adding Other Heads

Drag the green view into the main view’s top-left corner. Recall that the green view had horizontal and vertical space constraints that determined its position in the parent view. It still has those, and they cause the frame of the view to be misaligned.

To fix this, use the Resolve Auto Layout Issues button and choose Update Constraints Constants. This will update the constraints to match the frame:

auto layout tutorial

The leading constraint now has size of zero, represented by a thick blue line at the left edge of the window. Although the view sits in the corner, it needs constraints to anchor it there:

Now you are going to start adding more views to show more people. Select the green view and press Command-C followed by Command-V to duplicate it. Move the duplicate into the top-right corner:

Notice that the T-bars are red. When you made the duplicate, it lost its constraints for the X and Y position. To fix that, pin the view to the top and the right edges of the window. Make sure to uncheck Constrain to margins.

auto layout tutorial

Duplicate two more times and put these copies in the bottom-left and bottom-right corners, respectively. The bottom-left view should have its leading and bottom pinned, while the bottom-right should have its trailing and bottom edges pinned to the superview.

Now it’s time to make the screen more colorful. Select each of the green views and change their backgrounds to a different color. Also change the label titles and the images view images to represent the programmers. In the end, your screen should look something like this:

Those are some good-looking programmers! :]

Run the app on the iPhone SE simulator. It looks good in portrait, but not in landscape:

auto layout tutorial

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

Select the fixed width and fixed height constraints from all four views and delete them. This is easiest in the Document Outline. If you run the app now, you’ll get something like this:

auto layout tutorial

Note: Some of the views are larger than others because of the intrinsic content size. The size of the image determines how large the image view is. The size of the text determines how large the label is. Taken together with the constraints for the margins, this determines the total size of each view.

50:50 Split

To achieve your desired layout, you’re going to set each view’s width and height to be 50% of the ViewController’s view. In Document Outline, Control-drag from the green Ray view to the Safe Area view:

While pressing Shift, click Equal Widths and Equal Heights, and then press Enter. This allows you to select multiple items. Once those constraints are active, Ray will fill the screen, which is not the intention. :]

In the Size inspector, click Edit on the Equal Width to Safe Area row in the Sibling & Ancestor Constraints section:

auto layout tutorial

In the multiplier field, enter 0.5 and press Enter. This will set the width of Ray’s view to be 50% of Ray’s container view. Repeat this for the Equal Height to Safe Area row. You should see that Ray is now the correct size:

Now repeat this for the remaining views. Build and run. Everything looks great!

auto layout tutorial

Where to Go From Here?

Download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.

Congratulations! Now you know what Auto Layout is all about, and you have some experience with the basics! There’s much more to learn. To keep learning, check out our Auto Layout tutorial video series.

If you have any questions or comments as you continue on your Auto Layout journey, join the forum discussion below.