SwiftUI onAppear is called 2 times while if else construction is used to show two ContentViews

Viewed 27

I am trying to implement the structure where I have two different views with if else.

Minimal reproducable example:

struct ContentView: View {

    @State private var shouldShowContentView1 = true

    var body: some View {
        ZStack {
            if shouldShowContentView1 {
                NavigationView {
                    ZStack(alignment: .center) {
                        ContentView1(shouldShowView: $shouldShowContentView1)
                    }
                }
            } else {
                NavigationView {
                    ZStack(alignment: .center) {
                        ContentView3()
                    }
                }
            }
        }
    }
}

struct ContentView1: View {

    @Binding private var shouldShowView: Bool
    @State private var shouldShowContent2: Bool = false

    init(shouldShowView: Binding<Bool>) {
        _shouldShowView = shouldShowView
    }

    var body: some View {

        NavigationLink(destination: ContentView2(shouldShowView: $shouldShowView), isActive: $shouldShowContent2) {}

        Button(action: {
            shouldShowContent2 = true
        }) {
            Text("Skip1")
        }
        .onAppear {
            print("ContentView1 Appeared")
        }
    }
}

struct ContentView2: View {

    @Binding private var shouldShowView: Bool

    init(shouldShowView: Binding<Bool>) {
        _shouldShowView = shouldShowView
    }

    var body: some View {

        Button(action: {
            shouldShowView = false
        }) {
            Text("Skip2")
        }
        .onAppear {
            print("ContentView2 Appeared")
        }
    }
}

struct ContentView3: View {
    var body: some View {
        Text("Hello, world!3")
            .padding()
            .onAppear {
                print("ContentView3 Appeared")
            }
    }
}

I am using this switch logic with two NavigationView because of internal need, so I am trying to switch between the first flow and the second flow using the @State shouldShowContentView1

When I press on Skip2 I correctly see ContentView3, but for some reason onAppear is called again on ContentView1 and ContentView2.

ContentView1 Appeared
ContentView2 Appeared
ContentView1 Appeared
ContentView3 Appeared
ContentView2 Appeared

Can't figure out why is this happening and how to fix it.

0 Answers
Related