I am placing a share button inside of a toolbar.
.toolbar {
ToolbarItem(placement: .navigationBarTrailing){
Menu {
Share()
} label: {
Label(title: {
Text("More actions")
}, icon: {
Image(systemName: "ellipsis.circle")
})
}
}
}
I need the position of the button for viewController.popoverPresentationController?.sourceRect
.
import SwiftUI
struct Share: View {
var body: some View {
GeometryReader { geo in
let frame = geo.frame(in: .global)
Button {
share(text: "Test", frame: frame)
} label: {
Label("Share", systemImage: "square.and.arrow.up")
Text(frame.debugDescription)
}
}
}
func share(text: String, frame: CGRect){
let viewController = UIActivityViewController(activityItems: [text], applicationActivities: nil)
let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
let window = windowScene?.windows.first
window?.rootViewController?.present(viewController, animated: true)
if UIDevice.current.userInterfaceIdiom == .pad {
viewController.popoverPresentationController?.sourceView = window
viewController.popoverPresentationController?.sourceRect = frame
}
}
}
However, the (global) coordinates of the frame while inside of the toolbar are (0.0, 0.0, 0.0, 0.0)
. It works if the button is elsewhere, like a VStack on the main screen.
Alternatively, is there a way to access the coordinates of the "More actions" menu label like ShareLink(item: "test")
seems to do?