Search code examples
swiftui

Disable swipe-back for a NavigationLink SwiftUI


How can I disable the swipe-back gesture in SwiftUI? The child view should only be dismissed with a back-button.


Solution

  • By hiding the back-button in the navigation bar, the swipe-back gesture is disabled. You can set a custom back-button with .navigationBarItems()

    struct ContentView: View {
        var body: some View {
            NavigationView{
                List{
                    NavigationLink(destination: Text("You can swipe back")){
                        Text("Child 1")
                    }
                    NavigationLink(destination: ChildView()){
                        Text("Child 2")
                    }
                }
            }
        }
    }
    
    struct ChildView: View{
        @Environment(\.presentationMode) var presentationMode
    
        var body:some View{
            Text("You cannot swipe back")
                .navigationBarBackButtonHidden(true)
                .navigationBarItems(leading: Button("Back"){self.presentationMode.wrappedValue.dismiss()})
        }
    }