How to push to UIViewController from SwiftUI View that is in NavigationController

Viewed 4949

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

My Scene Delegate showing how my View is instantiated :

    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?

1 Answers

You would have to wrap your UIViewController in a SwiftUI View and then navigate to that.

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

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

Related