5

所以我有一个 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") }
        }
    }
}

这是打印出来的结果:

Page 1 init
Page 2 init
Page 1 appearing
Page 1 disappearing
Page 1 appearing

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

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
4

1 回答 1

0
    TabView {
        NavigationView {
            VStack {
                Color.red
                    .onAppear {
                        print("appear : red")
                    }
                    .onDisappear {
                        print("disappear : red")
                    }
            }.onAppear {
                print("appear")
            }
        }
    }

在 iOS 15 beta 模拟器上测试

输出:

appear : red
appear
disappear : red
appear : red
于 2021-08-23T01:57:21.187 回答