3

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.

Uncommon
  • 3,323
  • 2
  • 18
  • 36

1 Answers1

0

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)
George
  • 25,988
  • 10
  • 79
  • 133
  • 2
    The question is, what are the consequences of ignoring the view controller? Presumably there is a reason why AppKit has `NSHostingView` while UIKit does not have `UIHostingView'. But it's not really obvious why that is. – Uncommon Apr 15 '21 at 20:55
  • 1
    @Uncommon Interesting question. I stumbled upon [this link](https://stackoverflow.com/a/56827040/9607863) and I am unsure as to why they do `addChild(controller)`. I have used the `UIView` directly, and I don't specifically see a reason why it isn't reasonable to use. It could be so they can access the [`children`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621452-children) of the view controller, but I am honestly not 100% sure on this. It is an interesting point. What I would say is if all you need is the view, this will work. Do correct me if you find good reasons to! – George Apr 15 '21 at 21:07
  • It is in place in order to coordinate the lifecycle of the child view controller. How would the child viewcontroller otherwise know whether it has appeared/disappeared – Petru Lutenco May 24 '22 at 09:40
  • does this actually work? I don't see Hello World appear at all – Paul Fitzgerald Dec 07 '22 at 14:40