Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does onAppear() execute twice when placed on elements inside a NavigationView in swiftUI? (Xcode 12.0)

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)

like image 532
Mac Wayne Avatar asked Jul 08 '20 05:07

Mac Wayne


1 Answers

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)
    }
}
like image 161
grenos Avatar answered Nov 12 '22 06:11

grenos