[英]How to Navigating from SwiftUI View to UIKit UIViewController
[英]How to call a UIViewController from SwiftUI
我有一個 SwiftUI TabView,第二個選項卡項需要顯示一個 UIViewController。 如何在第二個選項卡中嵌入 UIViewController?
class MyUIVC: UIViewController {.....}
以下是我想要的一些偽代碼:
struct myTabView: View {
@State var selectedTab: Int = 0
var body: some View {
mySwiftUIView
.tabItem { Text("First Tab") }
.tag(0)
MyUIVC //This is what I want to do with my UIViewController
.tabItem { Text("Second Tab") }
.tag(1)
}
}
您需要使用UIViewControllerRepresentable.
橋接 ViewController UIViewControllerRepresentable.
. Apple 在此處提供了有關如何使用它的文檔:
https://developer.apple.com/documentation/swiftui/uiviewcontrollerrepresentable
此外,在他們的 SwiftUI 課程中有一個關於它的工作示例,最著名的是標題為“與 UIKit 交互”的課程,可以在這里找到:
https://developer.apple.com/tutorials/swiftui/interface-with-uikit
他們正在使用的示例 ViewController 如下所示:
struct PageViewController: UIViewControllerRepresentable {
var controllers: [UIViewController]
func makeUIViewController(context: Context) -> UIPageViewController {
let pageViewController = UIPageViewController(
transitionStyle: .scroll,
navigationOrientation: .horizontal)
return pageViewController
}
func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
pageViewController.setViewControllers(
[controllers[0]], direction: .forward, animated: true)
}
class Coordinator: NSObject {
var parent: PageViewController
init(_ pageViewController: PageViewController) {
self.parent = pageViewController
}
}
}
話雖如此,橋接 ViewController 的核心和靈魂是:
1) 為繼承自UIViewControllerRepresentable
的 ViewController 創建一個具有唯一名稱的結構
2)實現函數makeUIViewController(context: Context)
,返回類型為UIViewController
3) 實現函數updateUIViewController(_ uiViewController: YourUIViewController, context: Context)
無返回
4) 根據需要,實現一個從NSObject
繼承的Coordinator
類以及您需要的任何委托協議。
還有一點取決於您需要 ViewController 做什么,但這應該讓您指向正確的方向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.