Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 46 ยท Views and Layout

VStack, HStack, ZStack and Spacer

Arrange SwiftUI views with VStack, HStack and ZStack. Learn alignment, spacing, Spacer, Divider and layout priority, plus a runnable model of how a row shares its width.

A SwiftUI body returns exactly one view, but screens contain many. Stacks are the containers that solve this: they take several child views and arrange them along one axis. HStack lays children out horizontally, VStack vertically, and ZStack front to back. Nearly every screen you will build is a nest of these three.

In the previous lesson you saw that modifiers wrap views. Stacks are the other half of composition: they combine views side by side. This lesson covers the three stacks, alignment and spacing, the flexible Spacer, and what happens when a row has too little room. The real SwiftUI code is read-only here, because iOS cannot run on this site; the runnable examples are small Swift models of the layout arithmetic.

Three stacks, three axes

HStack Children side by side, left to right.
VStack Children one below another.
ZStack Children layered, back to front.

Nest them freely to build any screen.

1 / 2

VStack and HStack

A VStack places its children top to bottom. An HStack places them left to right. Both take the children as a trailing closure, which is a result builder (see Swift features SwiftUI relies on).

Swift
struct ProfileHeader: View {
    var body: some View {
        HStack {
            Image(systemName: "person.circle.fill")
                .font(.largeTitle)
            VStack(alignment: .leading) {
                Text("Mira Okafor")
                    .font(.headline)
                Text("iOS developer")
                    .foregroundStyle(.secondary)
            }
        }
    }
}

This is the shape of countless list rows: an icon beside a two-line text block. The stack sizes itself to fit its children. It does not fill the screen unless a child asks for that.

Alignment

Alignment controls where children sit on the cross axis, the direction perpendicular to the stack. In a VStack that is horizontal, so .leading, .center and .trailing apply. In an HStack the cross axis is vertical, so you choose .top, .center, .bottom, .firstTextBaseline or .lastTextBaseline.

Swift
VStack(alignment: .leading, spacing: 4) {
    Text("Title")
    Text("A longer subtitle line")
}

HStack(alignment: .firstTextBaseline) {
    Text("$")
    Text("49")
        .font(.largeTitle)
}

The default is .center, which is why a VStack of different-width texts looks centered. Aligning on text baselines keeps the dollar sign and the large number sitting on one line, which .center would not.

Spacing

The spacing parameter sets the distance between neighbouring children. If you leave it out, SwiftUI picks a system value that depends on the kinds of views next to each other. Pass spacing: 0 to remove gaps completely, or a number for a fixed gap. Spacing is between children, never before the first or after the last.

ZStack: layering

A ZStack draws its children on top of each other. The first child is at the back, the last in front. The stack is as big as its largest child, and alignment (a two-dimensional value such as .bottomTrailing) decides where the smaller children sit.

Swift
ZStack(alignment: .bottomTrailing) {
    RoundedRectangle(cornerRadius: 16)
        .fill(.blue)
        .frame(width: 160, height: 100)
    Text("New")
        .padding(8)
        .background(.white, in: Capsule())
        .padding(8)
}

Use a ZStack for badges, overlays and backgrounds that depend on content. For a decoration that should simply follow one view's size, the .background and .overlay modifiers are usually cleaner.

Spacer: taking the leftover room

A Spacer is a view with no appearance that expands along the stack's axis. It soaks up all the free space, which pushes its neighbours apart.

Swift
HStack {
    Text("Wi-Fi")
    Spacer()
    Text("Home network")
        .foregroundStyle(.secondary)
}

Here the label sticks to the left edge and the value to the right, because the spacer between them takes every point that the two texts do not need. Two spacers share the free room equally, so Spacer(); Text("Centered"); Spacer() centers the text. You can also set a minLength so a spacer never collapses below a gap.

Let us model this. The simplified Swift below places fixed-width children and splits what is left among the spacers. It ignores minimum lengths, so it shows the idea rather than every real rule.

Swift How a row shares its width

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice the last case: without a spacer, the leftover room simply stays unused, and the stack does not fill the width. A stack is only as wide as its content needs.

Divider and layout priority

A Divider is a thin line that runs across the stack's cross axis: horizontal inside a VStack, vertical inside an HStack.

When a row is too narrow for all its children, SwiftUI has to decide who gives way. By default it shrinks the views that are most flexible, such as text, which truncates with an ellipsis. You can steer this with .layoutPriority(_:). Views with a higher priority are laid out first and get the space they want; lower-priority views share what remains.

Swift
HStack {
    Text("A very long song title that does not fit")
        .lineLimit(1)
    Text("3:42")
        .layoutPriority(1)
}

Without the priority, the duration might be squeezed too. With it, the duration keeps its full width and only the title truncates. The default priority is 0, and the value is only compared between siblings of the same stack.

Swift Giving priority to one child

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

This is a toy model (proportional shrinking is an assumption), not SwiftUI's real algorithm. What it shows is the effect you see on screen: the prioritized child keeps its size and the other one gives way.

When a Text truncates unexpectedly, check the stack first. A sibling that cannot shrink (an Image, a fixed frame) plus a Spacer often leaves too little room for the text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a VStack, which alignment values make sense?

    A VStack arranges children vertically, so alignment applies on the horizontal cross axis: leading, center or trailing.
  2. 2. What does a Spacer do?

    A Spacer has no appearance. It grows to fill free space, which pushes its siblings apart.
  3. 3. Which child is drawn in front inside a ZStack?

    A ZStack draws children in order, so later children cover earlier ones.
  4. 4. What does .layoutPriority(1) on a child of an HStack do?

    Higher-priority siblings are laid out first. Lower-priority siblings share what remains, so they are the ones that truncate.

Summary

  • HStack, VStack and ZStack combine several views into one; nest them to build screens.
  • alignment positions children on the cross axis; spacing sets the gap between children.
  • A stack is only as large as its content needs, unless a child (such as a Spacer) expands.
  • Spacer takes free space along the axis; multiple spacers share it equally.
  • Divider draws a separator; .layoutPriority decides who shrinks first in a tight row.

Next, find out exactly how a parent and its children negotiate sizes in How SwiftUI Layout Works.