1. 单独创建并移植UIHostingController
import UIKit
import SwiftUI
class Controller1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 设置背景颜色
self.view.backgroundColor = .white
// 创建并添加 SwiftUI 视图
let contentView = UIHostingController(rootView: ContentView())
addChild(contentView)
contentView.view.frame = self.view.bounds
self.view.addSubview(contentView.view)
contentView.didMove(toParent: self)
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("This is ContentView")
.font(.largeTitle)
.padding()
// 其他内容
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
2. 直接继承自UIHostingController
class CreationController: UIHostingController<CreationView> {
typealias ContentView = CreationView
private let viewModel: ContentView.ViewModel
deinit {
HXLogger.debug("Running ☠️ \(Self.self) 💀 deinit")
}
init(fromWorks: Bool, config: ContentView.Config) {
viewModel = .init(fromWorks: fromWorks, config: config)
super.init(rootView: ContentView(viewModel: viewModel))
}
@MainActor required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if #available(iOS 17.0, *) {
.default
} else {
viewModel.isDark ? .lightContent : .darkContent
}
}
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 14.8, *) {
initialize()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #unavailable(iOS 14.8) {
initialize()
}
}
private func initialize() {
view.backgroundColor = viewModel.isDark ? .hex(0x03141A) : .white
view.layer.masksToBounds = true
navigationController?.setNavigationBarHidden(true, animated: false)
viewModel.closeHandler = { [unowned self] isBackward in
if let navigationController {
if isBackward {
navigationController.popViewController(animated: true)
} else {
navigationController.popToRootViewController(animated: true)
}
} else {
dismiss(animated: true)
}
}
viewModel.deleteSheetHandler = { [unowned self] in
showDeleteSheet()
}
viewModel.reportHandler = { [unowned self] in
ReportView.with(templateId: viewModel.config.workId).show()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !viewModel.isFromWorks {
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if !viewModel.isFromWorks {
navigationController?.interactivePopGestureRecognizer?.isEnabled = true
}
}
func showDeleteSheet() {
HXPresentView()
.configSubtitle("Are you sure to delete it?".localized)
.configCertainText("Delete".localized)
.configCancelText("Cancel".localized)
.configCertain { [weak self] in
guard let self else { return true }
self.viewModel.handleDeleteRequest()
Tracker.click(.creationDelete, params: [.workId(self.viewModel.config.workId)])
return true
}
.show()
}
}
网友评论