本文介绍了如何检测返回到 SwiftUI 中 NavigationView 的根视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到ContentView出现了!"消息仅第一次/onAppear
似乎被称为
I see "ContentView appeared!" message only first time/ onAppear
seems to be called ones
是否可以通过其他方式检测回根?
Is it possible to detect return to the root in any other way?
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailView()) {
Text("Hello World")
}
}
}.onAppear {
print("ContentView appeared!")
}.onDisappear {
print("ContentView disappeared!")
}
}
}
struct DetailView: View {
var body: some View {
VStack {
Text("Second View")
}.onAppear {
print("DetailView appeared!")
}.onDisappear {
print("DetailView disappeared!")
}
}
}
推荐答案
NavigationView
在 view
之间持久化.所以当你在它们之间推送和弹出时,它实际上不是 appear
和 disappear
.所以你需要在 NavigationView 的内容上设置 modifier
s,NOT NavigationView
它自己:
NavigationView
is persist between view
s. So it's not actually appear
and disappear
when you push and pop between them. So you need to set the modifier
s on the NavigationView's content, NOT the NavigationView
it self:
NavigationView {
NavigationLink(destination: DetailView()) { Text("Hello World") }
.onAppear { print("ContentView appeared!") }
.onDisappear { print("ContentView disappeared!") }
}
这篇关于如何检测返回到 SwiftUI 中 NavigationView 的根视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!