在视图控制器中呈现swiftUI
这是UIKit当中的代码
import UIKit
import SwiftUI
class ViewController: UIViewController {
let button: UIButton = {
let button = UIButton(frame: CGRect(x: 50, y: 50, width: 50, height: 50))
button.setTitle("tap", for: .normal)
button.backgroundColor = UIColor.black
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.view.addSubview(button)
button.addTarget(self,action: #selector(presentSwiftUIView), for: .touchUpInside)
}
@objc func presentSwiftUIView(){
print("yes")
let swiftUiView = SwiftUIView()
let hostingController = UIHostingController(rootView: swiftUiView)
hostingController.modalPresentationStyle = .fullScreen
present(hostingController, animated: true)
}
}
UIHostingController
是 SwiftUI 框架中的一个类,它允许你在 UIKit(或 AppKit)中使用 SwiftUI 视图。这个类的主要目的是在 UIKit 应用程序中嵌入 SwiftUI 视图,并且可以作为 UIKit 视图控制器的一部分来管理 SwiftUI 视图的生命周期。
这样我们就能在UIKit视图控制器中呈现一个swiftUI的视图
将SwiftUI视图添加到UIKit视图
@objc func addChildSwiftUIView(){
let swiftUiView = SwiftUIView()
let hostingController = UIHostingController(rootView: swiftUiView)
// 将 UIHostingController 添加为子视图控制器
addChild(hostingController)
// 将 UIHostingController 的视图添加到当前视图
self.view.addSubview(hostingController.view)
hostingController.view.frame = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 100, height: 100)
// 完成添加子视图控制器的过程,这一步十分必要,方便UIKit管理视图
hostingController.didMove(toParent: self)
}
其中didmove方法是在通知主控制器成功添加视图当中,便于UIKit的管理