我有一个NavigationView
和以下的视图结构ViewA -> ViewB -> ViewC
,我正在尝试找出如何检测当ViewB
返回到ViewA
ViewB -> ViewA
。这是我的代码:
struct ViewA: View {
var body: some View {
NavigationView {
NavigationLink{
ViewB()
}label: {
Text("Go to ViewB")
}
}
}
}
struct ViewB: View {
@Environment(\.presentationMode) var presentationMode: Binding
var body: some View {
NavigationLink{
ViewC()
}label: {
Text("Go to ViewC")
}
.onAppear{
print("onAppear \(presentationMode.wrappedValue.isPresented)")
}
.onDisappear{
print("onDisappear \(presentationMode.wrappedValue.isPresented)")
}
}
}
struct ViewC: View {
var body: some View {
Text("ViewC")
}
}
使用以下代码:
.onAppear{
print("onAppear \(presentationMode.wrappedValue.isPresented)")
}
.onDisappear{
print("onDisappear \(presentationMode.wrappedValue.isPresented)")
}
通过上述代码,我可以检测到当ViewC变为ViewB(根据控制台输出onAppear true
)。但我的问题是如何检测ViewB -> ViewA
的变化。
你们中是否有人知道如何完成这项任务或者是否有其他方法来检测这种变化?
非常感谢您的帮助。
ViewA
中像在ViewB
中一样做呢?在ViewA
中添加.onAppear{ print("----> onAppear ViewA") }
和.onDisappear{ print("----> onDisappear ViewA") }
。从一个视图消失并出现在另一个视图中的组合应该可以让您确定从ViewB
到ViewA
。但请注意,NavigationView
已被弃用,您应该使用NavigationStack
,这将使所有这些变得更加容易。 - workingdog support Ukraine