Search code examples
swiftswiftuiswiftui-sharelink

How to trigger another action when tapping a ShareLink


Currently using SwiftUI built in ShareLink functionality. I need to trigger a different action at the same time that ShareLink is pressed. This ShareLink is nested within a SwiftUI Menu.

How would I accomplish this?

Here is an example of my code:

struct ContentView: View {
    var body: some View {
        VStack {
            Menu("options") {
                Button {
                    print("button 1 is pressed")
                } label: {
                    Text("Test Menu Button")
                }
            
                shareLinkButton
                    .onTapGesture {
                        print("ShareLink triggered!")
                    }
            }
        }
    }
    
    
    var shareLinkButton: some View {
        ShareLink(item: URL(string: "https://stackoverflow.com/")!) {
            Label {
                Text("hello")
                    .onTapGesture {
                        print("HELLO")
                    }
            } icon: {
                Image(systemName: "apple.logo")
            }
        }
        .onTapGesture {
            print("ShareLink triggered!")
        }
    }
}

It is just a basic Menu with two buttons in them.

None of the onTapGestures get triggered at any point. I've also tried to wrap ShareLink within a button, like this:

        Button {
            ShareLink(item: URL(string: "https://stackoverflow.com/")!) {
                Label {
                    Text("hello")
                        .onTapGesture {
                            print("HELLO")
                        }
                } icon: {
                    Image(systemName: "apple.logo")
                }
            }
            print("test")
        } label: {
            Label {
                Text("hello")
                    .onTapGesture {
                        print("HELLO")
                    }
            } icon: {
                Image(systemName: "apple.logo")
            }
        }

Which triggers the print statement, but not the ShareLink.

I've also tried to use simultaneousGesture as well, but, no luck.

I do not want to use UIKit for my solution, I'd like to keep this a SwiftUI implementation.

Any suggestions? :)


Solution

  • There is no way you can catch when trigger ShareLink inside Menu. The only way to handle this is UIActivityViewController with Representable. :(

    Apple says:

    People tap or click on a share link to present a share interface. The link typically uses a system-standard appearance; you only need to supply the content to share