Chapters

Hide chapters

iOS Animations by Tutorials

Sixth Edition · iOS 13 · Swift 5.1 · Xcode 11

Section IV: Layer Animations

Section 4: 9 chapters
Show chapters Hide chapters

8. Introduction to Auto Layout
Written by Marin Todorov

Auto Layout is a system of APIs that allow developers to express the dimension and position of UI elements in terms relative to the size of the screen and/or various device treats.

Auto Layout allows for a wide range of UI customizations, from slight variations of views’ widths to aesthetically fill the space of various screens, to completely rearranging the UI layout from rows to columns when switching between portrait and landscape orientations.

This chapter is for the readers that need an iOS Animations by Tutorials crash course on Auto Layout. You will need to have the skills taught in this chapter in order to proceed to the next one, where you’ll learn about animations in Auto Layout.

If you are already well-versed in building Auto Layout interfaces, you can skip ahead to Chapter 9, “Animating Constraints.”

For those of you out there still reading and eager to dive into using Auto Layout, imagine first, if you will, a world without Auto Layout…

You’re in charge of creating a new app for your company.

Your design, built with Interface Builder, would look like something like the following:

With the view positioned exactly as you want it, you then check its frame in the Size Inspector.

The position and size of your view are expressed in absolute values of points. That looks okay, so you launch the iPhone 8 Simulator to see your beautiful app in action:

What happened? You view is no longer centered. The problem is that the view’s position is expressed in points; you had designed your app in Interface Builder with the iPhone SE in mind, but since the iPhone 8 has a different screen resolution, your view appears off-center.

When you press Cmd + Right arrow to rotate the Simulator, the situation gets even worse:

The auto-resizing and re-positioning system in Interface Builder provides a partial solution to these kinds of problems. However, if you’re serious about creating dynamic and beautiful user interfaces that work with multiple device sizes and orientations, then you’ll need to start using Auto Layout.

Auto Layout to the rescue

Since you’re no longer living in the Twilight Zone and Auto Layout is a reality, consider the same project from before, but this time using Auto Layout:

With Auto Layout it’s easy to indicate that the center.y property of the text view should equal the center.y value of its superview. This means the text view will always be centered within its superview – independent of the screen on which the app runs.

You could also choose to set the width of the text view to 90% of the width of its superview; this leaves a nice 5% margin of white space around the text.

With this simple set of rules in hand, Auto Layout happily rearranges the elements in your UI to look good on any device, in any orientation.

“So what’s the catch?” you might be thinking. Well, there isn’t a catch per se, it’s just that you need to think differently.

Once you place your app in the hands of Auto Layout, you no longer set the bounds, frame or center properties of a view. If you were to try, UIKit will force a layout pass on your UI using Auto Layout, which will set everything back to the positions and sizes determined by your constraints.

Not being able to change these properties means that you can’t animate those properties either! Therefore to move your views around or change their shape, you’ll instead alter the Auto Layout rules — or constraints — that define where a view appears as well as its size.

But before you can animate constraints, you first need to learn how to create constraints, and more importantly, how they work.

Auto Layout Constraints

Open the starter project for this chapter in Xcode, then build and run your project to see what it looks like:

That’s right — the project has no UI at all. Your job in this chapter is to build a simple interface with Auto Layout and learn how constraints work.

The project does, however, include some starter code:

  • ViewController.swift: This class contains a few outlets to be connected to the views you’ll create in Interface Builder. Further, it contains table view delegate and data source methods, which you will use once you add a table view to the user interface.

  • HorizontalItemList.swift: This is a scroll view subclass, which shows a scrollable list of images. You’ll use this class in the next chapter.

Your goal is to build a very simple dynamic UI, which will have the following appearance on different devices and orientations:

Adding the top menu

First you’re going to add the top menu to the interface file. Visually, the menu will resemble a navigation bar.

In the next chapter, you’re going to make it expand and contract, and offer the user much more than a plain old navigation bar.

Open Main.storyboard and drag a custom view onto the existing view controller:

Use the Attributes Inspector to change the background color of the view to Group Table View Background Color:

Resize the new view to more or less resemble a navigation bar in size; you don’t need to worry about the exact dimensions right now. Make sure to snap the view to the top, left and right edges of the safe area:

Now that you can actually see the view, you can constrain it to stay always in that top area where you mocked it up in Interface Builder.

Note: Be sure to position the bar on the top of the safe area. This will make sure it looks right on all device types.

Creating your first constraint

Select the view, and then click on the Pin button — the middle button — in the toolbar in the bottom right corner of Interface Builder (a.k.a. the square TIE fighter button):

In the resulting popup menu, uncheck Constrain to margins and click the left, top, and right indicators to create three constraints:

Click the Add 3 Constraints button to add them to your view and close the popup.

Each constraint is a relationship expressed as an equation; the top constraint you just created would be represented like so:

View.Top = 1 * Safe Area.Top + 0

The top position of your new view will always be 0 pt from the top of the safe area.

Constraining the menu height

Select your view again and click again on the Pin button to get the constraints popup.

This time you want to create a constraint to fix the Height of the menu view to a constant value. In the popup, you will see the height of the view you set while positioning the view.

Check the checkbox next to Height and then click Add 1 Constraint at the bottom.

Now you’ve fixed the height of your menu bar forever. However, what if you wanted the height to be precisely 44pt? Let’s look into how to edit the already created Height constraint.

Deselect the current UI element and select your view once more then switch to the Size Inspector, the second tab from the right in the assistant editor:

Here, you’ll see all the constraints for the selected view:

You probably don’t have the Height fixed to 44pt so let’s fix that. Click the Edit button on the offending constraint and set it to 44pt, like so:

As soon as you do that you’ll see the menu resize accordingly:

Use View as: at the bottom of the storyboard to see that the layout is preserved across different screen sizes:

It works! The menu view is always pinned to the top and sides and has a height of 44pt. And even better — you understand how it works. Now you can start to populate that menu.

Adding the menu title

Drag a label onto the menu view, set its Text to Packing List, the Alignment to Center, and the Font size to 21.0 points. Your label should look as follows:

Now you need to center the label in its parent view. Select the label, and while holding the Ctrl key, drag with the mouse (in a diagonal direction) to the menu bar like so:

Click Center Horizontally in Container to center the label horizontally within the menu. Then, while holding the Ctrl key, drag again and click Center Vertically in Container to align the label vertically within the menu.

This creates constraints that fix the label’s center coordinate to the center coordinate of the menu:

Things don’t look quite right in Interface Builder; unless you placed the label precisely in the center of the menu view you’ll probably see something like the following:

Resolving Auto Layout issues

While designing in Interface Builder it’s possible that dragging views around can result in a difference between where views are placed in Interface Builder, and where your constraints would place them at runtime (i.e. the view is positioned manually on a spot that doesn’t reflect the applied constraints).

In the image above, the label just happens to be placed precisely in the vertical center of the menu, so Interface Builder notes this with a blue guide indicating the vertical constraint has been satisfied.

The orange guide, however, indicates that the horizontal alignment constraint is “broken”. Interface Builder shows you the current frame of your view in solid orange along with the frame that the constraint expects in a dashed orange line.

To fix this, ensure the label is selected, then click the Update frames button in the bottom right corner of Interface Builder as shown below:

Your label will automatically jump to the correct position and size:

The two new constraints on your label translate to the following equations:

Superview.CenterX = 1.0 * UILabel.CenterX + 0.0

Superview.CenterY = 1.0 * UILabel.CenterY + 0.0

Next, you’ll add the + button on the right hand side of the screen.

Adding a menu button

Drag a button onto the menu view. Set its Title to +, Font Size to 27.0, and align it as shown below:

Click the Pin button and check the Trailing Space constraint. Click Add 1 Constraint to pin the button to the right edge of the view controller.

So far you’ve created only constraints between a view and its superview. But you don’t have to constrain yourself in this way anymore — pardon the pun! You can create relationships between views on the same level of the view hierarchy as well.

For example, it would be a good idea to vertically align the + button to the title label. This way they will always line up, even if you move the title label.

Aligning views with Auto Layout

Select the button and hold Ctrl on your keyboard as you drag with the mouse from the button to the label. Release the mouse button when the label activates and you will see a popup menu like so:

Click on Center Vertically to align the button vertically to the label.

Make sure the constant is 0 (zero) and the First Item of the new constraint is the + button, as shown in the image below:

This is important because you want to attach the button to the title, instead of vice versa. If you see Packing List.Center Y as the first item, click on the drop down next to it and then click Reverse First and Second Item to switch the two items.

Now select the button again and click on the Update frames button, if it’s enabled. This ought to remove any warnings in Interface Builder (if there were any). You are almost done with creating the user interface; the only missing element is the table view.

Adding and constraining a table view

Drag a table view and drop it in the empty view controller space:

Since you’re getting quite skilled at using Auto Layout in Interface Builder, you’ll likely breeze through the steps to set up your table view.

Click the Pin button and uncheck Constrain to Margins, enable the top, left, bottom, and right constraints and set them all to 0; just be careful not to press Enter prematurely before entering all values:

Click Add 4 Constraints to add the constraints to your view and close the popup:

Note that the constraints you create via the Pin button popup relate to the table’s nearest neighbor, not necessarily its parent view. In the case of the left, right, and bottom constraints above this is the superview — the view controller’s view.

In the case of the top constraint above, there’s a neighboring view closer to the table’s top – the menu. So Interface Builder automatically picks up that view for the top constraint.

You’re done setting up the basic constraints for your app! You now have a good understanding of how Auto Layout works and how to setup constraints and relationships between views in Interface Builder. Thanks to these new skills of yours, you’ll get to create some cool new animations for your Packing List project in the next chapter.

Finalizing the UI

There’s just two more things to take care of before you move on: cleaning up what white bar at the top, and connecting the existing outlets to their corresponding UI elements.

The white bar is because you’re using safe area layout guides. That area at the top will be taken up by the status bar and / or notch on applicable devices. You don’t want to put any of your content in there, but you don’t want it to stand out as a separate color either. Select the white area, which will select the main view of the view controller. Open the attributes inspector and change the background color to Group Table View Background, which is the same color you used for your navigation bar. The white area will disappear and your “navigation bar” will look taller.

Note: Real navigation controllers stretch the navigation bar to the top of the screen and use the safe area margins to position their content, but that’s a little advanced for this chapter!

Ctrl-drag with the mouse from the view controller object to the table view, then select tableView from the popup menu:

Then Ctrl-drag from the view controller to the title and select titleLabel:

Do the same for the + button and select buttonMenu:

Now Ctrl-drag from the button back to the view controller and select actionToggleMenu.

Next, drag from the table view to the view controller and select dataSource:

Once again, Ctrl-drag from the table view to the view controller but this time select delegate:

All that’s left is to give your table a prototype cell. Drag a table view cell object onto the table view, like so:

Then open the Attributes Inspector and enter Cell for the Identifier:

At long last, build and run your project; the existing table view code in ViewController.swift will pick up the newly connected outlets and populate the table with data:

The app not only looks good, but it has a rock-solid layout thanks to Auto Layout. Give the app a whirl in different Simulators — both iPhone (notched and non-notched) and iPad — and change the orientation to check it out for yourself!

Key points

  • With Auto Layout, you don’t set the position and size of your views in absolute values but rather express them as relative to the size of the screen or other views in the view hierarchy.
  • You create new constraints between views by dragging between them while holding the Ctrl key and then choosing the type of constraint from a popup menu.
  • Once a view has its constrains set (fully determining its position and size) it will be automatically laid out on any screen size by Auto Layout.

Challenges

Your challenge this time is simple: simply head on in to the next chapter! By now you understand Auto Layout in some detail, which is an important prerequisite for the work you’re about to do in the next chapter, which deals with animations and Auto Layout.

See you in the next chapter!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.