Using SwiftUI View from UIKit
3 min
In Storyboard
SwiftUI views can be used inside UIKit apps by creating classes that conforms to UIHostingController with type of SwiftUI view we want use.
import SwiftUI
struct TestView: View {
var body: some View {
Text("Hello, World!")
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
class TestViewHostingController: UIHostingController<TestView> {
required init?(coder aDecoder: NSCoder) {
super.init(rootView: TestView())
}
}
- Create a class that conforms to UIHostingController with type of SwiftUI view in this case type is TestView
- Add required init?(coder aDecoder: NSCoder) that calls super.init(rootView: TestView()), which creates UIHostingController with TestView as rootView.
- In Storyboard add UIHostingController and set its class to the TestViewHostingController
From code
- Instantiate UIHostingController with the SwiftUI view as rootView
- Present instantiated hosting controller like UIViewController
import SwiftUI
let hostingController = UIHostingController(rootView: SwiftUIView())
present(hostingController, animated)
// or navigationController?.pushViewController(hostingController, animated: true)