Does UIHostingController have to be in the view controller hierarchy?

2.6k views Asked by At

I want to embed some SwiftUI in my UIKit-based UI, and unfortunately Apple doesn't provide UIHostingView, only UIHostingController. Can I more or less ignore that controller and just use its view, or do I really need to add it as a child view controller as well? What happens if I don't?

The problem is that finding the parent view controller can be difficult in some contexts. UIView itself doesn't know anything about view controllers, so I'd have to come up with my own way of keeping track of which is the "current" view controller. And I'd rather not do that unless it's actually necessary.

So far in my experiments it's working fine without adding UIHostingController as a child. Device rotation is handled appropriately, and SwiftUI's dark mode override (.colorScheme()) even works through the embedding.

1

There are 1 answers

4
George On

With UIHostingController(rootView:) you just pass in a SwiftUI View.

You can treat it as a UIView by doing:

let myView = UIHostingController(rootView: Text("Hello world!")).view

And then add it as a subview for example:

let parent = UIView()
parent.addSubview(myView)