在UIKit中調(diào)用SwiftUI悯姊,需要使用UIHostingController對SwiftUI的view進(jìn)行包裝,代碼如下:
import UIKit
import SwiftUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
SwiftUiView.textStr = "SwiftUiView"
SwiftUiView.color = .red
let vc = UIHostingController(rootView: SwiftUiView())
vc.view.frame = self.view.bounds
self.view.addSubview(vc.view)
}
}
// SwiftUI
struct SwiftUiView: View {
static var textStr : String = ""
static var color : Color?
var body: some View{
VStack(){
Spacer()
HStack{
Spacer()
Text(SwiftUiView.textStr)
Spacer()
}.padding(0)
Spacer()
}.background(SwiftUiView.color).padding(0)
}
}
效果如下: