4

I have seen many examples of how to add a SwiftUI view into a UIKit view using Container Views, which assume you have access to the parent UIViewController on the UIKit side. I have a case where I can't do that; specifically, I want to add a SwiftUI view to the MKAnnotationView's detailCalloutAccessoryView, where I just have a UIView to attach to, but no parent UIViewController in UIKit. What should I do in this case?

When looking around, I found a (seemingly) compelling answer: https://github.com/khuffie/swiftui-mapkit-callout

In this solution, you create a UIView from scratch, then create a UIHostingController with the SwiftUI view, and add the UIHostingController's view to the top-level UIView (with auto-layout constraints), and just return the top UIView, without having to do anything with container views (like call didMoveToParentView). And it works, in that it displays the SwiftUI view correctly inside the annotationView callout. BUT when the map is dragged around, the callout view seems to move with it (the UIHostingView from the view debugger), but the underlying SwiftUI view doesn't actually move along with it, so if you have buttons on that SwiftUI view, you can't tap them at the place where they appear.

It's a little strange. This is what I see in the view debugger ... first, with the 'HostingView' selected:

View debugger with hosting view selected

Then selecting the actual SwiftUI View (which doesn't show on screen, but is where all the subviews and tap targets are):

View debugger with SwiftUI view selected

BTW, it can be reproduced with the sample code on the repository itself. When you run the sample app, open the callout button, then drag the map around, then inspect it with the view debugger.

I've created an issue for this at the repository: https://github.com/khuffie/swiftui-mapkit-callout/issues/1

I'm wondering if this issue is happening because the UIHostingController doesn't get added to any parent view controller? Is that a hard requirement that isn't being fulfilled here, or can it work otherwise? Are there any other solutions for this I can try? I've tried doing this without SwiftUI, making a UIView with a subview with buttons on it using Interface Builder, and that view behaves correctly as expected, so I'm guessing there's something about the interface between UIKit and SwiftUI that is messing up. Is there a better way to set that up for this case, where we don't have access to a UIViewController on the UIKit side?

Z S
  • 7,039
  • 12
  • 53
  • 105
  • I'm seeing the same thing (and also on iOS 15). Layout is completely broken unless you add the `UIHostingController` as a child view controller. – NachoSoto Sep 10 '21 at 01:03

0 Answers0