当 TabView 内的 NavigationView 时 SwiftUI onAppear 调用两次

and*_*rei 7 tabview navigationview swiftui onappear

所以我有一个 TabView,其中每个选项卡都嵌入在 NavigationView 中。在每个选项卡第一次出现时,我都会收到以下生命周期调用 onAppear()、onDisappear()、onAppear()。所以看起来 onAppear 被调用了两次。这只会发生第一次。如果我导航回同一个选项卡,则只会调用 onAppear(),而且只会调用一次。

这是一个最小的例子:

struct Page1: View {
    init() { print("Page 1 init") }
    
    var body: some View {
        NavigationView {
            Text("Page 1")
                .onAppear(perform: { print("Page 1 appearing") })
                .onDisappear(perform: { print("Page 1 disappearing") })
        }
    }
}

struct Page2: View {
    init() { print("Page 2 init") }
    
    var body: some View {
        NavigationView {
            Text("Page 2")
                .onAppear(perform: { print("Page 2 appearing") })
                .onDisappear(perform: { print("Page 2 disappearing") })
        }
    }
}

struct ContentView: View {
    var body: some View {
        TabView {
            Page1().tabItem { Text("Page 1") }
            Page2().tabItem { Text("Page 2") }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是打印出来的结果:

Page 1 init
Page 2 init
Page 1 appearing
Page 1 disappearing
Page 1 appearing
Run Code Online (Sandbox Code Playgroud)

如果我单击第二个选项卡,会发生以下情况

Page 1 init
Page 2 init
Page 1 appearing
Page 1 disappearing
Page 1 appearing
// here I clicked on second tab
Page 2 appearing
Page 2 disappearing
Page 2 appearing
Page 1 disappearing
Run Code Online (Sandbox Code Playgroud)

小智 0

    TabView {
        NavigationView {
            VStack {
                Color.red
                    .onAppear {
                        print("appear : red")
                    }
                    .onDisappear {
                        print("disappear : red")
                    }
            }.onAppear {
                print("appear")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

在 iOS 15 beta 模拟器上测试

输出:

appear : red
appear
disappear : red
appear : red
Run Code Online (Sandbox Code Playgroud)

  • 选项卡视图中有一个选项卡。当您在两个选项卡之间切换时会出现问题 (2认同)