Z S
Z S

Reputation: 7501

SwiftUI: pass view information to UIKit

I have a UIKit and AppKit app, and I am displaying a SwiftUI view within it via UIHostingController / NSHostingController. The view has some buttons on it, and I want to pass back the tap event back to a UIKit/AppKit view controller to show UIAlertController from the button that got tapped (I would prefer to use ActionSheet within SwiftUI but it isn't supported on macOS). I pass a delegate through the hosting controller into the SwiftUI view, and use that to call back into the UIKit/AppKit view. But to display a UIAlertController (or even UIActivityViewController), I would need to get some information about the sourceView and sourceRect from the SwiftUI view, else it might crash on iPad.

How do I pass back that information, from the SwiftUI view into the UIKit/Appkit app? I guess the sourceView could be the SwiftUI view on display, but how do I read (and pass back) the rect of the SwiftUI button that was tapped?

Upvotes: 2

Views: 398

Answers (1)

Z S
Z S

Reputation: 7501

I found a way to do this. Since the button is a few layers of subviews down from the top-level SwiftUI, I gave that parent view a 'name', by using:

.coordinateSpace(name: "CalloutParentView") 

Then I wrapped the button in a GeometryReader, and in the button handler, I got the 'rect' by using:

geometry.frame(in: .named("ParentView")

I passed that through the delegate to the hosting UIViewController, and that can use the SwiftUI view as the sourceView and this rect as the sourceRect

Upvotes: 0

Related Questions