swiftswiftuinavigation

NavigationLink doesn't work inside of sheet view


I created a few buttons inside of a sheet view

struct PlusMenu: View {
    @Environment(\.dismiss) var dismiss
    @State var scaleChange = true
    var buttons = ["cup.and.saucer", "takeoutbag.and.cup.and.straw", "carrot", "fork.knife","equal.square"]
    var body: some View {
        VStack{
            HStack{
                Spacer()
                Button(action: {
                    dismiss()
                }, label: {
                    Text("Cancel")
                        .font(customFont(20, "-Black"))
                })
                .foregroundColor(.black)
                .padding(.top)
            }
            
            LabelledDivider(label: "Actions")
            
            Spacer()
            buttonList(start:0, end: 3)
            buttonList(start:3, end:buttons.count)
            Spacer()
        }
        .padding(.horizontal)
    }
    
    func buttonList(start:Int, end:Int) -> some View{
        HStack{
            ForEach(buttons[start..<end], id:\.self){ buttonName in
                Spacer()
                NavigationLink {
                    Text("Enter")
                } label: {
                    Image(systemName: buttonName)
                        .padding()
                        .background(Circle().stroke(.semiGray, lineWidth: 3).shadow(radius: 3))
                        .foregroundColor(.black)
                }

                Spacer()
            }
        }
        .padding(.vertical)
    }
}

This is my view for sheet enter image description here

But the main problem is when I click the button, it doesn't navigate to the next destination page. it works in the preview but not on device.

And I don't have navigationStack in this page is because I have that at my root view.

Do we allow to have navigationLink inside of sheet view?


Solution

  • AFAIK, sheet need their own NavigationStack. So in your .sheet(...), try using:

     .sheet(isPresented: $showingSheet) {
         NavigationStack {  // <--- here
             PlusMenu()
         }
     }
    

    Alternatively you could try using NavigationStack(path: $navPath), see: NavigationStack. Passing the navPath to the .sheet(item: $navPath)