SwiftUI:检测 NavigationView 返回主视图

use*_*482 5 swiftui swiftui-navigationview swiftui-view xcode14.3

我有一个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")
    }
}
Run Code Online (Sandbox Code Playgroud)

使用以下代码:

        .onAppear{
            print("onAppear \(presentationMode.wrappedValue.isPresented)")
        }
        .onDisappear{
            print("onDisappear \(presentationMode.wrappedValue.isPresented)")
        }
Run Code Online (Sandbox Code Playgroud)

使用上面的代码我可以检测 ViewC 何时变为 ViewB (每个控制台输出onAppear true)。但我的问题是如何检测何时ViewB -> ViewA

你们中的任何人都知道如何实现这一点,或者是否有办法检测到这一点?

我非常感谢你的帮助

Chr*_*isR 1

这是一个基于新解决方案的解决方案NavigationStack,它可以让您记录导航路径(如 @workingdog 提到的):

struct ViewA: View {
    
    @State private var navigationPath: [String] = []
    
    var body: some View {
        NavigationStack(path: $navigationPath) {
            NavigationLink(value: "B") {
                Text("Go to ViewB")
            }
            .navigationDestination(for: String.self) { destination in
                if destination == "B" {
                    ViewB()
                } else {
                    ViewC()
                }
            }
        }
        .onChange(of: navigationPath) { newValue in
            print(newValue)
            if newValue == [] {
                print("Coming from ViewB to ViewA") // trigger your action here
            }
        }
    }
}

struct ViewB: View {

    var body: some View {
        NavigationLink(value: "C") {
            Text("Go to ViewC")
        }
    }
}

struct ViewC: View {
    
    var body: some View {
        Text("ViewC")
    }
}
Run Code Online (Sandbox Code Playgroud)