SwiftUI ZStack first element is not displayed

541 views Asked by At

I'm new to SwiftUI, and I have a simple app with a ZStack:

struct ContentView: View {
    @State var num : Int = 1
    
    var body: some View {
        NavigationView{
            ZStack{
                Text("asd")
                    .foregroundColor(.blue)
                    .frame(width: 400, height: 400, alignment: .center)
                    .background(.blue)
                VStack{
                    List{
                        ListItem()
                        ListItem()
                    }
                }
                .toolbar{
                    Button{
                        num+=1
                    } label: {
                        Label("Add", systemImage: "plus")
                    }
                }
            }
        }
    }
}

The problem is that the blue frame with the text is not displayed: enter image description here

Why is this happening?

2

There are 2 answers

1
Steven-Carrot On

You are using ZStack to wrap up everything.

Solution: Change from ZStack to VStack.

NavigationView{
        VStack{ //this part
3
Gavin Morrow On

It is because the Text View is underneath the List in the ZStack.

If you move the Text to after the list, it will be shown on top.

ZStack {
    VStack{
        List {
            ListItem()
            ListItem()
        }
        .listStyle(.insetGrouped)
    }
    .toolbar{
        Button{
            num+=1
        } label: {
            Label("Add", systemImage: "plus")
        }
    }
    
    Text("asd")
        .foregroundColor(.blue)
        .frame(width: 400, height: 400, alignment: .center)
        .background(.blue)
}