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.
With
UIHostingController(rootView:)
you just pass in a SwiftUIView
.You can treat it as a
UIView
by doing:And then add it as a subview for example: