UIStackView Tutorial for iOS: Introducing Stack Views

Learn how to simplify your iOS layouts with UIStackView. Layout a series of views horizontally or vertically, using alignment, distribution and spacing. By Ehab Amer.

Leave a rating/review
Download materials
Save for later
Share
Update note: Ehab Amer updated this tutorial for Swift 5, iOS 12 and Xcode 10. Jawwad Ahmad wrote the original.

Have you ever needed to add or remove views from a view during runtime and adjust the layout of views beside it? Maybe you adjusted some constraints or used a third-party library to do that work. Perhaps it wasn’t something at run time but one new view you wanted to jam between other views in your storyboard.

In these cases, you need to alter several constraints. You may find yourself removing all constraints in the area and adding them all over again.

UIStackView has simplified such tasks. You can easily lay out a series of views horizontally or vertically within a stack view and set it up in a way that the views are automatically adjusted to the available space using properties such as alignment, distribution and spacing. Enjoy! :]

Note: This tutorial assumes basic familiarity with Auto Layout. If you’re new to Auto Layout, check out the Beginning Auto Layout video tutorial.

Getting Started

Start by downloading the project materials using the Download Materials button at the top or bottom of this tutorial. Build and run the starter project in Xcode using the iPhone 8 Simulator. You’ll see the following:

This is the Vacation Spots app. It suggests a list of places to get away from it all. Before going anywhere, you’re going to solve a few problems with the app using Stack Views.

Exploring Vacation Spots

Go to the info view for London by tapping on London. At first glance, the view may look okay, but it has a few issues:

  1. Look at the row of buttons at the bottom of the view. Because of the fixed spacing between them, they don’t adapt to the screen width. To get a better look at the problem, rotate the simulator to landscape orientation by pressing Command-left arrow.

  1. Tap Hide next to WEATHER. This hides the text, but it doesn’t reposition the section below it, leaving a block of blank space.

  1. The section ordering needs improvement. It would be more logical if WHAT TO SEE appeared after WHY VISIT instead of positioning the weather section between them.
  2. The bottom row of buttons is too close to the bottom edge of the view in landscape mode. It’ll look better if you decrease the spacing between the sections — but only in landscape mode.

Now that you have an idea of the improvements you’ll be making, it’s time to dive into the project. Open Main.storyboard. It will open with an initial device view. Make sure it shows iPhone 8 as the selected device.

This has no effect at runtime but will help you see how the screens should look on that device. You can change the selected device any time by clicking another icon. Hovering the mouse over an icon reveals its corresponding devices.

which, when pressed, reveals the list of available devices, laid out vertically:

Note: If you reduce the Interface Builder canvas width (approximately below 650 pixels), the UI for changing device changes a little bit. The devices list is collapsed into a Device dropdown:

Now, take a close look at Spot Info View Controller:

You’re probably wondering What’s with the colors?

These labels and buttons have background colors that won’t show at runtime. In the storyboard, they’re visual aids to help show how changing various properties of a stack view affects the frames of its embedded views.

If at any point you’d like to see the background colors while running the app, you can temporarily comment out the following lines in viewDidLoad() inside SpotInfoViewController.

// Clear background colors from labels and buttons
for view in backgroundColoredViews {
  view.backgroundColor = UIColor.clear
}

Any outlet-connected label has a placeholder text that matches the outlet variable name. This makes it easier to tell which labels will have their text updated at runtime. For example, the label with text <whyVisitLabel> is connected to:

@IBOutlet var whyVisitLabel: UILabel!

Time to get started!

Your First Stack View

First, you’ll fix the spacing between the buttons on the bottom row. A stack view can distribute its subviews along its axis in various ways. One way is by setting equal spacing between each view.

Fortunately, embedding existing views into a new stack view is a piece of cake. First, select all the buttons at the bottom of the Spot Info View Controller scene by clicking on one, then command-clicking on the other two. Open the outline view by using the Show Document Outline button at the bottom-left of the storyboard canvas.

Verify that you have selected all three buttons.

They appear highlighted in the outline view. You can also command-click on each button in the outline view to select them.

Once selected, click the Embed In button in the Auto Layout toolbar at the bottom-right of the storyboard canvas. A menu with available embed options will appear. Choose Stack View:

Xcode will embed the buttons in a new stack view for you.

Stack View Constraints

While the stack view takes care of positioning the buttons, you still need to add Auto Layout constraints to position the stack view itself.

When you embed a view in a stack view, it loses the constraints it had to other views. For example, prior to embedding the buttons in the stack view, the top of the Submit Rating button had a vertical spacing constraint to the bottom of the RATING label:

Select the Submit Rating button and verify that it no longer has any constraints attached to it:

You can also look at the Size inspector (Option-Command-5) to verify that there are no constraints:

Sometimes it’s hard to select a specific element in a crowded storyboard’s view controller. You can select the element from the outline view, or use Shift and right-click or Control-Shift-click on the view you want to select. This gives you a context menu that shows the view hierarchy at the location you clicked. Select the stack view by clicking on it in the menu.

Now that you have the Stack View selected, you can add constraints to it.

Click the Add New Constraints button in the Auto Layout toolbar to show the Add New Constraints pop-up.

First, add a checkmark to Constrain to margins. Then, add the following constraints to the edges of your stack view:

Top: 20, Leading: 0, Trailing: 0, Bottom: 0

Double-check the numbers for the top, leading, trailing, and bottom constraints. Make sure you have turned on the four red I-beams and Constrain to margins. Then, click Add 4 Constraints.

Now the stack view is the correct size, but it has stretched the first button to fill in any extra space.