【问题标题】:How to push to UIViewController from SwiftUI View that is in NavigationController如何从 NavigationController 中的 SwiftUI View 推送到 UIViewController
【发布时间】:2020-12-26 07:03:35
【问题描述】:

我有一个 SwiftUI ViewUINavigationController 内的场景委托实例化 我想从 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()

我怎样才能做到这一点?

【问题讨论】:

    标签: ios swift uinavigationcontroller swiftui


    【解决方案1】:

    您必须将 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 here

    【讨论】:

    • 虽然使用这种方式可以达到你的目的,但我不推荐这种混合方式,因为NavigationLink似乎还不稳定。我更喜欢使用 UIKit 中的 UINavigationController 作为基础容器,如果使用 SwiftUI 视图比使用 UIKit 更方便地制作任何你想要的视图。
    • 怎么不稳定?使用它会创建另一个导航吗?或者它在同一个导航上的推动,用代码发布一个关于这个的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2012-03-15
    • 2021-05-25
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    相关资源
    最近更新 更多