Search code examples
swiftuiswiftui-navigationlink

SwiftUI : NavigationLink and the show Sheet Button in the List item works same time


I have a list item with some text stuff, navigationLink and button to show .sheet.When I click on either navigation link or show sheet button both navigation destination and the sheet appear.How to avoid this behaviour?

Note: This is minimal produceable code.

struct ContentView: View {
    @State var shouldSheetShow:Bool = false;

    var body: some View {
        NavigationView{
            List{
                VStack(alignment: .leading){
                    Text("Some Text Stuff")
                    NavigationLink(
                        destination: Text("navigation link"),
                        label: {
                            Text("Navigate To some view")
                                .background(Color.green)
                        })

                    Button(action: {
                        self.shouldSheetShow = true
                    }, label: {
                        HStack{
                            Text("Show sheet")
                        }
                        .background(Color.blue)
                        .sheet(isPresented: $shouldSheetShow, content: {
                            Text("sheet")
                        })

                    })
                }
                .frame(width: 300, height: 150, alignment: .center)
                .background(Color.gray)
            }

        }
    }
}

List Item


Solution

  • A possible solution is to replace the Button with Text plus an onTapGesture

    Replace

    Button(action: {
            self.shouldSheetShow = true
        }, label: {
            HStack{
                Text("Show sheet")
            }
            .background(Color.blue)
            .sheet(isPresented: $shouldSheetShow, content: {
                Text("sheet")
            })
    
        })
    

    with

    Text("Show sheet")
            .background(Color.blue)
            .sheet(isPresented: $shouldSheetShow, content: {
                Text("sheet")
            })
            .onTapGesture {
                self.shouldSheetShow = true
            }