|

How to Set ZStack Background Color in iOS SwiftUI

In SwiftUI, ZStack is a container view that arranges its child views along the z-axis, in other words, stacking them on top of each other. One common use-case is to set the background color for a ZStack. This blog post will guide you on how to do just that!

ZStack Overview

ZStack is a non-scrollable view that stacks its children on top of each other, aligning them in the center. It’s an essential tool for managing overlapping views. Now, let’s see how we can change the background color.

Set Background Color in ZStack

Setting a background color in ZStack is a straightforward task. You only need to add a colored shape to the ZStack.

Step 1: Create a ZStack

First, you need to define a ZStack in your SwiftUI View.

ZStack {
  Text("This is a ZStack")
}

Step 2: Add a Colored Shape to ZStack

In order to set a background color, we can add a Color view. It should be the first child of the ZStack to act as the background.

ZStack {
  Color.blue
  Text("This is a ZStack")
}

The Color.blue view will be displayed behind the Text view, acting as a background. You can use any color or even gradients instead of a solid color.

swiftui hstack background color

Following is the complete code for reference.


import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
          Color.blue
          Text("This is a ZStack")
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

ZStacks offer an intuitive way to manage overlapping views in SwiftUI. By placing a colored Color view as the first child in the ZStack, you can effectively set a background color for your entire ZStack view.

Similar Posts

Leave a Reply