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

5

我有一个通过场景代理实例化的 SwiftUI View,它被包含在一个 UINavigationController 中。

我想从这个 SwiftUI View 推出另一个 UIViewController

下面是我的场景代理代码,展示了如何实例化我的 View

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

我该如何实现这个?

1个回答

8
你需要将你的UIViewController包装在一个SwiftUI View中,然后导航到该视图。
例如:
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
}

并且可以在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()
    }.   
}

在SwiftUI中包装ViewControllers的详细信息请阅读此处


虽然你可以通过这种方式实现你的目标,但我不推荐这种混合方式,因为NavigationLink似乎仍然不稳定。如果使用UIKit中的UINavigationController作为基础容器,并且使用SwiftUI视图作为内容视图更方便制作任何想要的视图,那么我更喜欢使用它。 - Kyokook Hwang
它为什么不稳定?使用它会创建另一个导航栏吗?还是它会推到相同的导航栏上?请用代码回答这个问题。 - Mohmmad S
2
所以你问了一个问题,然后自己回答,并将自己的答案设为已采纳? - Atikul Gazi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接