Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know NavigationView is popped back in SwiftUI?

When user taps on the back button, can we get the event and do something?

I have tried with onDisappear for the view, but the order of child disappearing and parent appearing is not desired. So I am looking for a way to hook to the back event.

like image 987
samwize Avatar asked Sep 12 '25 22:09

samwize


2 Answers

Pedro's answer is the right approach. In my case, I'm using NavigationStack and binding it to a path array of an enum type I defined with each case representing a screen. I used the onChange modifier and checked of the case corresponding to the screen has been removed from the path array, this means the screen has been popped from the stack (either by user interaction with the Back button or programmatically), then I can run the logic I want.

enum Route: Hashable {
    case b
}

struct ViewA: View {
    @State private var path = [Route]()

    var body: some View {
        NavigationStack(path: $path) {
            NavigationLink("Go to B", value: Route.b)
        }
        .onChange(of: path) {
            if path.isEmpty {
                // All screens popped.
                // Add logic to handle this case here.
            }
        }
    }
}
like image 171
alobaili Avatar answered Sep 15 '25 11:09

alobaili


You can use the modifier onDisappear, I dont understand your exact case because you need the exact event of back.

struct ContentView: View {
    @State var isPresented: Bool = false

    var destination: some View {
        Text("Detail")
                .onDisappear(perform: {
                    print("On Disappear")
                })
    }

    var body: some View {
        NavigationView {
            NavigationLink(destination: destination, isActive: $isPresented) {
                Text("Main")
            }
        }
    }
}
like image 44
93sauu Avatar answered Sep 15 '25 13:09

93sauu