In the previous post ( How to use UIKit in SwiftUI) we explored the possibility to use
SwiftUI. Today I want to cover the other way round, using
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.
Apple provides a very basic
UIViewController subclass for hosting
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).
You simply init
let vc = UIHostingController(rootView: Text("Hello World"))
Then use it just like normal
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.
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
More detail can be found in Better dependency injection for Storyboards in iOS13.