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.
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.
}
}
}
}
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")
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With