How to use SwiftUI in UIKit

Sarun W.
4 min readDec 25, 2019

--

In the previous post ( How to use UIKit in SwiftUI) we explored the possibility to use UIKit in SwiftUI. Today I want to cover the other way round, using SwiftUI in UIKit project. I interest in this approach more, since all iOS projects right now are UIKit and rewrite everything from the ground up with SwiftUI for a sake of change wouldn't be possible, especially if you work for a client. So you would end up continue with UIKit or gradually adopt SwiftUI in your new component.

I want to know the complexity of adopting it in UIKit codebase, so when the time comes I can make sure the transition would go as smooth as possible.

Initialization

Apple provides a very basic UIViewController subclass for hosting SwiftUI, UIHostingController for UIKit / NSHostingController for AppKit / WKHostingController for WatchKit.

Nothing much you can do with this class, you just initialize it with SwiftUI's view. You have two choices here, via code with init(rootView: Content) and via interface builder with init?(coder: NSCoder, rootView: Content).

Init programmatically

You simply init UIHostingController with SwiftUI's view.

let vc = UIHostingController(rootView: Text("Hello World"))

Then use it just like normal UIViewController.

Init in interface builder

Xcode 11 introduced a new component in Interface Builder, Hosting View Controller. A Hosting View Controller is a UIViewController that hosts a SwiftUI view hierarchy.

You have 2 ways to set SwiftUI view to this Hosting View Controller.

IBSegueAction

You add a Hosting View Controller to your storyboard and create a segue to it. Then Control-drag from the segue into the presenting view controller (view controller that initiate push/present) to create an IBSegueAction, where you return a UIHostingController with your rootView.

More detail can be found in Better dependency injection for Storyboards in iOS13.

--

--

Sarun W.

iOS Developer at Oozou — Code & design iOS app — Follow me on https://twitter.com/sarunw for everything iOS — Blogging weekly at http://sarunw.com