Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Understanding ZStack & VStack in SwiftUI
Written by Team Kodeco

In SwiftUI, ZStack and VStack are two fundamental container views that allow you to arrange and layer views on the screen. ZStack layers views along the Z-axis, meaning it stacks them on top of each other, with the last view in the list appearing at the front. VStack, on the other hand, arranges views vertically from top to bottom.

Here’s an example that combines ZStack and VStack to create an interesting layered and stacked view:

struct ContentView: View {
  var body: some View {
    ZStack {
      VStack {
        Text("Top")
          .padding()
          .background(Color.green)
        Spacer()
          .frame(height: 20)
        Text("Middle")
          .padding()
          .background(Color.yellow)
        Spacer()
          .frame(height: 20)
        Text("Bottom")
          .padding()
          .background(Color.red)
      }

      Image(systemName: "sun.max.fill")
        .resizable()
        .frame(width: 100, height: 100)
        .foregroundColor(.orange)
    }
  }
}

Your preview should look like this:

Use a ZStack to create a layer.
Use a ZStack to create a layer.

First, the VStack creates a vertical stack of three Text views labeled “Top”, “Middle” and “Bottom”. Each Text view has padding around it and a different colored background. Between each Text view, a Spacer with a fixed height of 20 points is used to create a clear separation.

The ZStack then layers an Image on top of this VStack. The image used is a system image named sun.max.fill, which is made resizable and scaled to a width and height of 100 points. The image color is set to orange using the foregroundColor view modifier.

In the resulting layout, the image appears on top of the stack of Text views due to the z-ordering behavior of the ZStack. By leveraging ZStack and VStack in your SwiftUI applications, you can create a broad array of visually appealing, stacked and layered views.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.