Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable swipe-back for a NavigationLink SwiftUI

Tags:

swiftui

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

like image 863
simibac Avatar asked Dec 21 '19 17:12

simibac


2 Answers

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()})
    }
}

like image 116
simibac Avatar answered Sep 19 '22 10:09

simibac


This answer shows how to configure your navigation controller in SwiftUI (In short, use UIViewControllerRepresentable to gain access to the UINavigationController). And this answer shows how to disable the swipe gesture. Combining them, we can do something like:

Text("Hello")
  .background(NavigationConfigurator { nc in
     nc.interactivePopGestureRecognizer?.isEnabled = false
  })

This way you can continue to use the built in back button functionality.

like image 25
arsenius Avatar answered Sep 19 '22 10:09

arsenius