How to use SwiftUI in a UIKit project

Did you know that SwiftUI can be use in UIKit project? To use SwiftUI in UIKit project, you have to make use of UIHostingViewController. It is a UIViewController that basically “host” a SwiftUI view.

Assuming you have a SwiftUI View named SwiftUIView like so:

1let swiftUIView = SwiftUIView()

Initializing it programmatically

To initialize it programmatically, set the SwiftUI View as the rootView of the UIHostingController.

1let vc = UIHostingController(rootView: swiftUIView)
2self.present(vc, animated: true, completion: nil)

Initializing it in Storyboard

Using it in Storyboard requires a little bit more work.

  1. First, add a Hosting View Controller and create a segue to it

    Search for UIHostingController

  2. Then, create an IBSegueAction where you can init the UIHostingController like so

1 @IBSegueAction func openSwiftUIView(_ coder: NSCoder) -> UIViewController? {
2     return UIHostingController(coder: coder, rootView: swiftUIView))
3 }

That’s it.

References:
  1. Apple documentation on UIHostingController