Menu
Coddy logo textTech

Spacer And ZStack

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 12 of 50.

A Spacer takes up all the free space in a stack. In an HStack it pushes the views before it to the left and the views after it to the right:

HStack {
    Text("Total")
    Spacer()
    Text("$12.50")
}

In a VStack, a Spacer pushes views apart vertically.

ZStack layers views on top of each other. The first view is at the back and each next one sits on top:

ZStack {
    Color.blue
    Text("On top")
        .foregroundStyle(.white)
}

Color.blue used as a view fills all the space it is given, so here it becomes a blue background behind the text.

challenge icon

Challenge

Easy

Make the total row span the width: add a Spacer between Total and $12.50 so the price is pushed to the right edge.

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground