我看到“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!")
        }
    }
}

最佳答案

NavigationViewview 之间保持不变。所以当你在它们之间推送和弹出时,它实际上不是 appeardisappear。所以你需要在 NavigationView 的内容 上设置 modifier s, NOT NavigationView 它自己:

NavigationView {
    NavigationLink(destination: DetailView()) { Text("Hello World") }

    .onAppear { print("ContentView appeared!") }
    .onDisappear { print("ContentView disappeared!") }
}

关于ios - 如何检测返回到 SwiftUI 中 NavigationView 的根 View ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59007068/

10-11 02:30