0

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?

BPDev
  • 397
  • 1
  • 9
  • 1
    Why not using popover modifier on the button ? You can also look at [this](https://stackoverflow.com/a/72035626/13944750) – Ptit Xav Jul 09 '23 at 06:55
  • @PtitXav For some reason, the sheet doesn't show up when it's inside a toolbar (does the sheet need to be at the root view?). The popover is necessary to avoid crashes on iPad (for the arrow of the share box to point to the button you clicked), I am not sure how I would put it directly on the button. – – BPDev Jul 09 '23 at 16:14

0 Answers0