Views and Layout Containers

Article · 2:00

Stacks, grids and ScrollView, and the single layout rule the whole framework follows.

A SwiftUI view is a struct that conforms to View and has a body. You do not build it once and mutate it; you describe what it should look like for the current data, and the framework rebuilds it whenever that data changes. Views are cheap, created and discarded constantly, which is only safe because they are value types holding no state of their own.

Layout in SwiftUI is one conversation repeated down the tree. The parent proposes a size, the child replies with the size it wants, and the parent places it. Nothing is positioned by coordinates. Once you have internalised that exchange, layout stops being guesswork - when a view is the wrong size, the question is always "what did its parent propose" or "what did it ask for".

The three containers you will use most are VStack, which arranges children top to bottom, HStack, left to right, and ZStack, back to front. Spacer expands to fill whatever is left, which is how things get pushed apart. For rows and columns of many items, LazyVGrid and LazyHGrid build only what is on screen. For anything taller than the display, wrap it in a ScrollView.

Keep a body short. When it grows past a screenful, pull a part of it into its own small view - there is no runtime cost, and the compiler's type checker gets dramatically faster.

import SwiftUI

struct ProfileCard: View {
    let name: String
    let role: String

    var body: some View {
        // ZStack: back to front. The card sits on a rounded background.
        ZStack {
            RoundedRectangle(cornerRadius: 16)
                .fill(.thinMaterial)

            // HStack: left to right.
            HStack(spacing: 14) {
                Image(systemName: "person.crop.circle.fill")
                    .font(.system(size: 44))
                    .foregroundStyle(.tint)

                // VStack: top to bottom, left-aligned.
                VStack(alignment: .leading, spacing: 4) {
                    Text(name).font(.headline)
                    Text(role).font(.subheadline).foregroundStyle(.secondary)
                }

                Spacer()      // pushes everything above to the left
            }
            .padding()
        }
        .frame(height: 90)
    }
}

#Preview {
    ScrollView {
        VStack(spacing: 12) {
            ProfileCard(name: "Ada Lovelace", role: "Engineering")
            ProfileCard(name: "Grace Hopper", role: "Compilers")
        }
        .padding()
    }
}