1诡延、在SwiftUI中使用UIKit控件古胆,需要遵循以下協(xié)議:
UIView使用需要遵循UIViewRepresentable協(xié)議。
UIViewController使用需要遵循UIViewControllerRepresentable協(xié)議
- 效果展示:(傳值:背景顏色)
代碼如下:
import SwiftUI
struct ContentView: View {
@State var isPush = false
var body: some View {
NavigationView {
VStack {
NavigationLink(isActive: $isPush) {
TestTempVC(color: .red)
}label: {
}
Button {
isPush = true
} label: {
Text("跳轉(zhuǎn)到TestVC")
}
}.navigationBarTitle("ContentView", displayMode: .inline)
.padding()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import UIKit
import SwiftUI
// 遵循UIViewControllerRepresentable協(xié)議
struct SwiftUICallSwift: UIViewControllerRepresentable {
var color : UIColor?
func makeUIViewController(context: Context) -> some UIViewController {
let vc = TestViewController()
vc.color = color
return vc
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}
// SwiftUI(此處的作用是為了設(shè)置導(dǎo)航,如果直接從上個(gè)頁面push到TestViewController桶良,導(dǎo)航返回按鈕點(diǎn)擊將無效)
struct TestTempVC: View {
@Environment(\.presentationMode) var presentationMode
@State var color : UIColor?
var body: some View{
VStack{
SwiftUICallSwift(color: color)
}.navigationBarTitle("TestViewController", displayMode: .inline)
.navigationBarBackButtonHidden(true)
.navigationBarItems(leading: Button(action: {
presentationMode.wrappedValue.dismiss()
}, label: {
Image("nav_back_black")
}))
}
}
// UIViewController
class TestViewController: UIViewController {
var color : UIColor?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = color ?? .orange
self.title = "TestVC"
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
label.textAlignment = .center
label.center = self.view.center
label.text = "這是一個(gè)Swift的ViewController"
self.view.addSubview(label)
}
}