Home > database >  SwiftUI ZStack first element is not displayed
SwiftUI ZStack first element is not displayed

Time:07-16

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?

CodePudding user response:

You are using ZStack to wrap up everything.

Solution: Change from ZStack to VStack.

NavigationView{
        VStack{ //this part

CodePudding user response:

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)
}
  • Related