[英]SwiftUI onAppear called twice when NavigationView inside TabView
So I have a TabView where each of the tabs is embedded in a NavigationView.所以我有一个 TabView,其中每个选项卡都嵌入在 NavigationView 中。 On first appear of each tab I get the following lifecycle calls onAppear(), onDisappear(), onAppear().
在每个选项卡第一次出现时,我得到以下生命周期调用 onAppear()、onDisappear()、onAppear()。 So it looks like onAppear gets called twice.
所以看起来 onAppear 被调用了两次。 This only happens the first time.
这只是第一次发生。 If I navigate back to the same tab, only onAppear() gets called, and only once.
如果我导航回同一个选项卡,只有 onAppear() 被调用,而且只有一次。
Here's a minimal example:这是一个最小的例子:
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") }
}
}
}
And here's the result printed out:这是打印出来的结果:
Page 1 init
Page 2 init
Page 1 appearing
Page 1 disappearing
Page 1 appearing
Here's what happens if I click on the second tab如果我单击第二个选项卡,会发生以下情况
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
TabView {
NavigationView {
VStack {
Color.red
.onAppear {
print("appear : red")
}
.onDisappear {
print("disappear : red")
}
}.onAppear {
print("appear")
}
}
}
Test on iOS 15 beta Simulator在 iOS 15 beta 模拟器上进行测试
The output: output:
appear : red
appear
disappear : red
appear : red
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.