我看到“ ContentView出现了!”仅是第一次发送消息/ onAppear
似乎被称为
是否可以通过其他任何方式检测到返回根目录?
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!")
}
}
}
答案 0 :(得分:1)
NavigationView
在view
个之间保持不变。因此,当您在它们之间推动并弹出时,它们实际上并不是appear
和disappear
。因此,您需要在 NavigationView的内容上设置modifier
,不要自行设置NavigationView
:
NavigationView {
NavigationLink(destination: DetailView()) { Text("Hello World") }
.onAppear { print("ContentView appeared!") }
.onDisappear { print("ContentView disappeared!") }
}
答案 1 :(得分:0)
找到了愚蠢的解决方案,但是它可以工作。只需在根视图内将onAppear()
添加到VStack
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailView()) {
Text("Hello World")
}
}.onAppear {
print("stack appeared!")
}
}.onAppear {
print("ContentView appeared!")
}.onDisappear {
print("ContentView disappeared!")
}
}
}