SwiftUI Stacks

Stacks are essential SwiftUI views that control the layout of elements in an app, including HStack, VStack, ZStack, LazyHStack, and LazyVStack.
Written by

Chris C

Updated on

May 01 2024

Table of contents

    Stacks are essential views that control the layout of elements in an app. This includes HStack, VStack, ZStack, and lazy stacks.

    Basic Code Examples

    There are three main types of stacks. HStack lays out child views horizontally, VStack lays them out vertically, and ZStack places views on top of one another.

    HStack {
        Text("Hello world!")
        Image(systemName: "circle")
    }
    
    VStack {
        Text("Hello world!")
        Image(systemName: "circle")
    }
    
    ZStack {
        Text("Hello world!")
        Image(systemName: "circle")
    }
    • HStack creates a layout where child views appear next to one another horizontally.
    • VStack creates a layout where child views appear in a vertical format.
    • ZStack creates a layout where child views appear on top of one another, which is useful for adding backgrounds or overlays.

    Alignment of Stacks

    Stacks can take an alignment parameter. HStack uses VerticalAlignment, while VStack uses HorizontalAlignment.

    HStack(alignment: .bottom) {
        Text("Hello world!")
        Image(systemName: "circle")
    }
    
    VStack(alignment: .leading) {
        Text("Hello world!")
        Image(systemName: "circle")
    }

    HStack can align its children to the bottom, center, or top. VStack can align its children to the leading edge, center, or trailing edge.

    Spacing between Children Elements

    HStack and VStack can take a spacing parameter, which adds space between each child view in the stack.

    HStack(spacing: 20) {
        Text("Hello world!")
        Image(systemName: "circle")
    }
    
    VStack(spacing: 100) {
        Text("Hello world!")
        Image(systemName: "circle")
    }

    The amount of spacing is determined by the number passed into the stack initializer.

    Lazy Stacks

    Lazy stacks are useful when your content goes beyond the screen size, such as in a scrollable list. They load views only as those views are needed, instead of creating every child view immediately.

    LazyHStack {
        ForEach(0..<100) { index in
            Text("\(index)")
        }
    }
    
    LazyVStack {
        ForEach(0..<100) { index in
            Text("\(index)")
        }
    }

    Stacks are not inherently scrollable. Wrap lazy stacks with a view such as ScrollView when you want scrolling behavior.

    ScrollView {
        LazyVStack {
            ForEach(0..<100) { index in
                Text("\(index)")
            }
        }
    }

    Tip: use regular stacks for small fixed layouts and lazy stacks for larger collections that appear in scroll views.