简体   繁体   English

如何从 NavigationController 中的 SwiftUI 视图推送到 UIViewController

[英]How to push to UIViewController from SwiftUI View that is in NavigationController

I have a SwiftUI View instantiated from the scene delegate inside a UINavigationController I would like to push to another UIViewController from the SwiftUI View我有一个从UINavigationController内的场景委托实例化的SwiftUI View ,我想从SwiftUI View推送到另一个UIViewController

My Scene Delegate showing how my View is instantiated :我的场景委托显示了我的View是如何实例化的:

    let vc = UIHostingController(rootView:SwiftUIView())
    let navigationControll = UINavigationController(rootViewController: vc)
    self.window?.rootViewController = navigationControll
    // Present window to screen
    self.window?.makeKeyAndVisible()

How can I achieve this?我怎样才能做到这一点?

You would have to wrap your UIViewController in a SwiftUI View and then navigate to that.您必须将UIViewController包装在 SwiftUI View ,然后导航到该View

For example例如

struct MyMasterViewController: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> MasterViewController {
        var sb = UIStoryboard(name: "Main", bundle: nil)
        var vc = sb.instantiateViewController(identifier: "MasterViewController") as! MasterViewController
        return vc
    }
    
    func updateUIViewController(_ uiViewController: MasterViewController, context: Context) {
    }
    
    typealias UIViewControllerType = MasterViewController
}

and call it simply in NavigationLink like this from SwiftUI View并从 SwiftUI View像这样在NavigationLink简单地调用它

struct SwiftUIView: View {
    var body: some View {
        NavigationLink(destination: MyMasterViewController()) {
                           Text("Show Detail View")
        }.navigationBarTitle("Navigation")
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }.   
}

Read more about Wrapping ViewControllers in SwiftUI here此处阅读有关在 SwiftUI 中包装 ViewControllers 的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM