簡體   English   中英

如何從 NavigationController 中的 SwiftUI 視圖推送到 UIViewController

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

我有一個從UINavigationController內的場景委托實例化的SwiftUI View ,我想從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()

我怎樣才能做到這一點?

您必須將UIViewController包裝在 SwiftUI View ,然后導航到該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 的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM