Mixing UIKit and SwiftUI with UIHostingController
A practical pattern for incrementally migrating UIKit view controllers to SwiftUI without breaking existing navigation involves using `UIHostingController`. Based on our Music Theory Learning app, this example demonstrates passing navigation context and handling two-way communication between UIKit and SwiftUI.
@objc
class TopicSelectionNGViewController: UIViewController {
let appModel: AppModel = AppModel.shared
private var hostingController: UIHostingController < TopicSelectionView >?
private func hostSwiftUIView() {
if hostingController != nil { return }
let rootView = TopicSelectionView(
navigationController: self.navigationController,
hostingViewController: self,
appModel: appModel
)
let hosting = UIHostingController(rootView: rootView)
hosting.view.translatesAutoresizingMaskIntoConstraints = false
addChild(hosting)
view.addSubview(hosting.view)
NSLayoutConstraint.activate([
hosting.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hosting.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hosting.view.topAnchor.constraint(equalTo: view.topAnchor),
hosting.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
hosting.didMove(toParent: self)
}
}
