TExcelTAD
Home › Swift › Stacks & Layout

SwiftUI Stacks & Layout

SwiftUI arranges views with stacks. Combine three of them — vertical, horizontal and layered — with Spacer, padding and frame, and you can build almost any screen without manual coordinates.

Note: SwiftUI code can't run in the browser. Each layout is followed by an HTML mock of the iPhone screen.

The three stacks

Stack Arranges children Alignment parameter
VStack top to bottom .leading, .center, .trailing
HStack left to right .top, .center, .bottom, .firstTextBaseline
ZStack on top of each other (back to front) .topLeading, .center, .bottomTrailing, …

Each stack also takes a spacing: value for the gap between children.

HStack and VStack together

A typical list row: an icon on the left, two lines of text, and a value pushed to the right with Spacer().

swift
import SwiftUI

struct TransactionRow: View {
    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: "cart.fill")
                .frame(width: 40, height: 40)
                .background(.green.opacity(0.2))
                .clipShape(Circle())
            VStack(alignment: .leading, spacing: 2) {
                Text("Groceries").font(.headline)
                Text("Today, 9:41").font(.caption).foregroundStyle(.secondary)
            }
            Spacer()
            Text("-$42.80").font(.headline)
        }
        .padding()
    }
}

The Spacer() expands to fill the free space, pushing the amount to the trailing edge:

html · try it yourself
<div style="width:340px;margin:12px auto;border:10px solid #1c1c1e;border-radius:44px;background:#fff;font-family:-apple-system,system-ui,sans-serif;padding:60px 0">
  <div style="display:flex;align-items:center;gap:12px;padding:16px">
    <div style="width:40px;height:40px;border-radius:50%;background:rgba(52,199,89,.2);display:flex;align-items:center;justify-content:center">🛒</div>
    <div style="display:flex;flex-direction:column;gap:2px">
      <span style="font-size:17px;font-weight:600">Groceries</span>
      <span style="font-size:12px;color:#8e8e93">Today, 9:41</span>
    </div>
    <div style="flex:1"></div>
    <span style="font-size:17px;font-weight:600">-$42.80</span>
  </div>
</div>

ZStack: layering

ZStack draws its children on top of one another — the first child is at the back. It is perfect for badges, overlays and backgrounds:

swift
struct Badge: View {
    var body: some View {
        ZStack(alignment: .topTrailing) {
            RoundedRectangle(cornerRadius: 16)
                .fill(.indigo)
                .frame(width: 120, height: 120)
            Text("3")
                .font(.caption.bold())
                .foregroundStyle(.white)
                .frame(width: 28, height: 28)
                .background(.red)
                .clipShape(Circle())
                .offset(x: 10, y: -10)
        }
    }
}
html · try it yourself
<div style="width:320px;height:300px;margin:12px auto;border:10px solid #1c1c1e;border-radius:44px;background:#fff;font-family:-apple-system,system-ui,sans-serif;display:flex;align-items:center;justify-content:center">
  <div style="position:relative;width:120px;height:120px;border-radius:16px;background:#5856d6">
    <span style="position:absolute;top:-10px;right:-10px;width:28px;height:28px;border-radius:50%;background:#ff3b30;color:#fff;font-size:12px;font-weight:700;display:flex;align-items:center;justify-content:center">3</span>
  </div>
</div>

How SwiftUI sizes views

Layout is a three-step conversation between parent and child:

  1. The parent proposes a size to the child.
  2. The child chooses its own size (a Text picks just enough room for its words; a Color takes everything offered).
  3. The parent places the child, using the alignment.

frame(width:height:) and frame(maxWidth: .infinity) change what a view proposes or accepts. This little Swift simulation shows how an HStack divides a row's width between fixed-size items and flexible spacers:

swift · try it yourself
enum Item {
    case fixed(String, width: Int)
    case spacer
}

func layoutRow(_ items: [Item], totalWidth: Int) {
    let fixedWidth = items.reduce(0) { sum, item in
        if case .fixed(_, let w) = item { return sum + w }
        return sum
    }
    let spacerCount = items.filter { if case .spacer = $0 { return true } else { return false } }.count
    let flexible = spacerCount > 0 ? (totalWidth - fixedWidth) / spacerCount : 0

    var x = 0
    for item in items {
        switch item {
        case .fixed(let name, let w):
            print("\(name) at x=\(x), width \(w)")
            x += w
        case .spacer:
            print("Spacer at x=\(x), width \(flexible)")
            x += flexible
        }
    }
}

layoutRow([.fixed("Icon", width: 40), .fixed("Title", width: 120), .spacer, .fixed("Price", width: 70)],
          totalWidth: 360)
Icon at x=0, width 40
Title at x=40, width 120
Spacer at x=160, width 130
Price at x=290, width 70

(The real algorithm also handles spacing, priorities and minimum sizes, but the idea is the same.)

Useful layout tools

Tool What it does
Spacer() flexible empty space along the stack's axis
.frame(maxWidth: .infinity, alignment: .leading) stretch to full width, content on the left
.padding(.horizontal, 20) inset content from the edges
ScrollView { } makes content scrollable
LazyVGrid(columns:) grid layout
GeometryReader read the size offered by the parent

Tip: Start with stacks and spacers; reach for GeometryReader only when you truly need exact sizes — it makes layouts harder to read.

Test yourself

Which stack places its children on top of each other?

  1. VStack
  2. HStack
  3. ZStack
  4. LazyVStack

What does Spacer() do inside an HStack?

  1. Adds a fixed 8-point gap
  2. Takes up all the remaining horizontal space
  3. Draws a vertical divider
  4. Nothing unless given a width

In SwiftUI's layout process, who decides a view's final size?

  1. Only the parent
  2. The child chooses, based on the size the parent proposes
  3. The screen
  4. Always the largest sibling