I have a NavigationView
and the following view structure ViewA -> ViewB -> ViewC
and I'm trying to figure out how to detect when ViewB goes back to ViewAViewB -> ViewA
. Here is my Code:
struct ViewA: View {
var body: some View {
NavigationView {
NavigationLink{
ViewB()
}label: {
Text("Go to ViewB")
}
}
}
}
struct ViewB: View {
@Environment(\.presentationMode) var presentationMode: Binding
var body: some View {
NavigationLink{
ViewC()
}label: {
Text("Go to ViewC")
}
.onAppear{
print("onAppear \(presentationMode.wrappedValue.isPresented)")
}
.onDisappear{
print("onDisappear \(presentationMode.wrappedValue.isPresented)")
}
}
}
struct ViewC: View {
var body: some View {
Text("ViewC")
}
}
With the following code:
.onAppear{
print("onAppear \(presentationMode.wrappedValue.isPresented)")
}
.onDisappear{
print("onDisappear \(presentationMode.wrappedValue.isPresented)")
}
with the code above I can detect when ViewC goes ViewB (per console output onAppear true
). But my question is how can detect when ViewB -> ViewA
.
Any of you knows how can accomplish this or if there is a way around to detect this?
I'll really appreciate your help
If you want to keep using
NavigationView
for compatibility with iOS 15 and earlier, then you can reliably be notified whenViewB
is popped by making the state ofViewA
’sNavigationLink
explicit.You used the
NavigationLink(destination:label:)
initializer, which means theNavigationLink
has a hidden flag that tracks whether it is active or not.Instead, store that flag yourself, and use a custom
Binding
with theNavigationLink(isActive:destination:label:)
initializer to be notified when theNavigationView
activates or deactivates the link.