Search code examples
iosswiftswiftui

SwiftUI: detecting the NavigationView back button press


In SwiftUI I couldn't find a way to detect when the user taps on the default back button of the navigation view when I am inside DetailView1 in this code:

struct RootView: View {
    @State private var showDetails: Bool = false
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailView1(), isActive: $showDetails) {
                    Text("show DetailView1")
                }
            }
            .navigationBarTitle("RootView")
        }
    }
}

struct DetailView1: View {
    @State private var showDetails: Bool = false
    var body: some View {
        NavigationLink(destination: DetailView2(), isActive: $showDetails) {
            Text("show DetailView2")
        }
        .navigationBarTitle("DetailView1")
    }
}

struct DetailView2: View {
    var body: some View {
        Text("")
            .navigationBarTitle("DetailView2")
    }
}

Using .onDisappear doesn't solve the problem as its closure is called when the view is popped off or a new view is pushed.


Solution

  • The quick solution is to create a custom back button because right now the framework have not this possibility.

    struct DetailView : View {
    
        @Environment(\.presentationMode) var mode: Binding<PresentationMode>
    
        var body : some View {
            Text("Detail View")
                .navigationBarBackButtonHidden(true)
                .navigationBarItems(leading: Button(action : {
                    self.mode.wrappedValue.dismiss()
                }){
                    Image(systemName: "arrow.left")
                })
        }
    }