FirstView Appeared
is printed twice. Once when the view first loads and again when the NavigationLink is selected.
import SwiftUI
struct FirstView: View {
var body: some View {
NavigationView{
ZStack{
Text("FirstView").onAppear(perform: {print("FirstView Appeared")})
NavigationLink(destination: SecondView()) {
Text("Goto SecondView")
}.offset(y: 50)
}
}
}
}
struct SecondView: View {
var body: some View {
Text("SecondView").onAppear(perform: {print("SecondView Appeared")})
}
}
Running the code above in Xcode 12.0 beta on both the simulator and a personal device produce the output below when the NavigationLink is selected:
FirstView Appeared
FirstView Appeared
SecondView Appeared
Is this duplication of onAppear() expected behavior?
If so, what best practices are there to load some data when firstview
is created and then upon return to firstview
(since onAppear() would attempt to load some data when navigating away from firstView
)
I know i'm a little late to the party but in case any one else has the same problem, just placing the lifecycle methods outside of the NavigationView
worked for me. I'm testing on Simulator - Xcode 12.2
struct fakeView1: View {
func didAppear() {
print("Appear")
}
func didDisappear() {
print("Disppear")
}
var body: some View {
NavigationView {
VStack {
Text("FAKE VIEW")
}
}
.onAppear { didAppear() }
.onDisappear { didDisappear() }
.navigationBarTitle("Fake View", displayMode: .inline)
}
}
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