首页 > 解决方案 > SwiftUI:导航到视图层次结构中的视图

问题描述

到目前为止我所拥有的:

我有两个视图,第一个 myContentView将加载到scene(_:willConnectTo:options:)方法中SceneDelegate(这是标准的)。我已将 a 嵌入NavigationView到我的ContentView. 第二个视图DetailView可以通过 导航到NavigationLink,要导航回来,您可以使用NavigationView.

struct ContentView: View {
    var body: some View {
        NavigationView {
            Form {
                NavigationLink(destination: DetailView()) {
                    Text("Navigate")
                }
            }
            .navigationBarTitle("Some Title")
        }
    }
}

struct DetailView: View {
    var body: some View {
        Text("Detail")
        .navigationBarTitle("Another Title")
    }
}

内部scene(_:willConnectTo:options:)方法SceneDelegate

let contentView = ContentView()

if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)
    window.rootViewController = UIHostingController(rootView: contentView)
    self.window = window
    window.makeKeyAndVisible()
}

我正在尝试做的事情:

现在我想DetailView根据connectionOptions.scene(_:willConnectTo:options:)SceneDelegate

我的问题:

当我只是根据替换let contentView = ContentView()时,我不再在我的视图层次结构中,因此我没有布局。let contentView = DetailViewconnectionOptionsContentViewNavigationView

问题:

如何导航到视图层次结构中的某个视图,而不会丢失由NavigationView另一个视图内部创建的任何导航功能(包括导航栏、后退按钮以及能够更深入地导航)?

标签: swiftnavigationswiftui

解决方案


使用NavigationLink(_,destination:,tag:,selection:)并绑定selection到来自connectionOptions.

有关详细说明和示例代码,请参阅https://nalexn.github.io/swiftui-deep-linking/


推荐阅读