介紹
混合開發(fā)主要是指在 SwiftUI 中使用 UIKit(SwiftUI 中使用 UIView 與 UIViewController)與在 UIKit 中使用 SwiftUI。通過混合開發(fā),開發(fā)者可以更靈活地利用 SwiftUI 與 UIKit 的各自優(yōu)勢,開發(fā)出功能強(qiáng)大且具有良好用戶體驗的應(yīng)用程序。
UIKit in SwiftUI
Apple 針對 UIView 與 UIViewController 提供了兩個 “表示器”,如下表所示。通過這兩個表示器可以很容易地將它們轉(zhuǎn)換成 SwiftUI 里面的 View。
UIKit | SwiftUI |
---|---|
UIView | UIViewRepresentable |
UIViewController | UIViewControllerRepresentable |
UIView in SwiftUI
UIViewRepresentable
- 要使 UIView 在 SwiftUI 中可用,需要用
UIViewRepresentable
對 UIView 進(jìn)行包裝。 -
UIViewRepresentable
中主要有 2 個方法需要實現(xiàn)。-
makeUIView()
:創(chuàng)建View
。 -
updateUIView()
:根據(jù)條件與業(yè)務(wù)邏輯設(shè)置View
的狀態(tài)。
-
案例
使用 UIKit 中的UIActivityIndicatorView
。
import SwiftUI
import UIKit
struct ActivityIndicator: UIViewRepresentable {
var isAnimating: Bool
// 如下的2個方法都是與UIKit相關(guān)
func makeUIView(context: Context) -> UIActivityIndicatorView {
let v = UIActivityIndicatorView()
v.color = .orange
return v
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {
if isAnimating {
uiView.startAnimating()
} else {
uiView.stopAnimating()
}
}
}
struct ContentView: View {
var isAnimating = true
var body: some View {
ActivityIndicator(isAnimating: isAnimating)
}
}
UIViewController in SwiftUI
UIViewControllerRepresentable
- 要使 UIViewController 在 SwiftUI 中可用,需要用
UIViewControllerRepresentable
對 UIViewController 進(jìn)行包裝。 -
UIViewControllerRepresentable
中主要有 2 個方法需要實現(xiàn)。-
makeUIViewController()
:創(chuàng)建UIViewController
。 -
updateUIViewController()
:根據(jù)條件與業(yè)務(wù)邏輯設(shè)置UIViewController
的狀態(tài)。
-
案例
使用 UIKit 中的UINavigationController
。
import SwiftUI
import UIKit
struct NavigationViewController: UIViewControllerRepresentable {
var vc: UIViewController
var title: String
func makeUIViewController(context: Context) -> UINavigationController {
let nvc = UINavigationController(rootViewController: vc)
return nvc
}
func updateUIViewController(_ navigationController: UINavigationController, context: Context) {
navigationController.viewControllers[0].title = title
}
}
struct ContentView: View {
var body: some View {
NavigationViewController(vc: UIViewController(), title: "UIViewControllerRepresentable")
}
}
SwiftUI in UIKit
UIKit 中使用 SwiftUI,需要通過UIHostingController
包裝 View,然后才能使用。
// 可以是復(fù)雜的ContentView
let vc = UIHostingController(rootView: ContentView())
// 也可以是簡單的Text等其他View
let vc = UIHostingController(rootView: Text("Hello SwiftUI"))