I've already read this existing thread on the issue and comments indicate that this is a bug and has been fixed on 11.7, but I'm still running into it on that version.
In summary:
when the app starts, your view View 1 fires an onAppear.
when I navigate to a child view (View 2) using a Navigation Controller , there is no onDisappear fired for View 1, but an onAppear does fire for View 2.
When you navigate back to View 1, you do not get a onAppear for View 1 or an onDisappear for (view 2).
Is there a workaround for a reliable way to trigger events when views appear/disappear? Or should I try hopping to the Xcode beta?
Example Code:
import SwiftUI
struct DetailView: View {
var body: some View {
Text("Detail view")
.onAppear(){
print("DetailView onAppear fired")
}
.onDisappear(){
print("DetailView onDisappear fired")
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView()) {
Text("Show detail view")
}
.navigationBarTitle("Master view")
}
.onAppear(){
print("ContentView onAppear fired")
}
.onDisappear(){
print("ContentView onDisappear fired")
}
}
}
You have added onAppear {..}
and onDisappear {..}
to the NavigationView which is still visible/appears in the DetailView. I guess, what you are getting is expected behaviour. onDisappear {..}
will be called only when view go off from screen.
Adding onAppear {..}
and onDisappear {..}
to your Text view will give the result as you expected.
struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: DetailView()) {
Text("Show detail view")
.onAppear {
print("ContentView onAppear fired")
}
.onDisappear {
print("ContentView onDisappear fired")
}
}
.navigationBarTitle("Master view")
}
}
}
ContentView onAppear fired
DetailView onAppear fired
ContentView onDisappear fired
ContentView onAppear fired
DetailView onDisappear fired
Thanks! 👨🏻💻
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