1

I want to specify a Link in my SwiftUI view, but I also want to register when/if that Link was actually tapped or not. What's the best way to do this? I tried adding an onTapGesture on the Link (which is a View I believe):

Link("Test", destination: URL(string: "testThreePanel://")!)
                    .onTapGesture {
                        print("Testing button link tapped")
                    }

But the onTapGesture doesn't get invoked on tapping the link.

Is there another way to do this?

Z S
  • 7,039
  • 12
  • 53
  • 105

3 Answers3

3

you could try this, works for me, but only on iOS15 / macOS12:

// iOS15 / macOS12 only 
Link("Test", destination: URL(string: "https://duckduckgo.com")!)
        .environment(\.openURL, OpenURLAction { url in
            print("---> testing link actioned")
            return .systemAction
        })
Z S
  • 7,039
  • 12
  • 53
  • 105
  • 3
    I tried this and got an error message: "Key path value type 'WritableKeyPath' cannot be converted to contextual type 'KeyPath'" – Z S Nov 12 '21 at 17:36
  • Is this supposed to only work in iOS 15.0 / macOS 12.0? Because I would need to support iOS14 / macOS11 as well. – Z S Nov 12 '21 at 17:39
  • yes you are correct, it works on ios 15, macos 12. There was no mention of io14 in the question. I'll delete my answer if it's no use to you. – workingdog support Ukraine Nov 12 '21 at 23:03
  • Thanks. You can label the original answer with the fact that it's only for iOS15 / macOS12, and I'll mark it as the answer. I don't believe there's another way to do it at this point. – Z S Nov 12 '21 at 23:32
2

Just enable firing both embedded and added gestures simultaneously.

struct ContentView: View {
    var body: some View {
        Link("Test", destination: URL(string: "testThreePanel://")!)
            .simultaneousGesture(
                TapGesture()
                    .onEnded { val in
                        print("Testing button link tapped \(val)")
                    }
            )
    }
}
Paul B
  • 3,989
  • 33
  • 46
1

For iOS 15 it also works if you remove the 'url' parameter, just in case you don't want to use it.

Link("Test", destination: URL(string: "https://duckduckgo.com")!)
.environment(\.openURL, OpenURLAction { _ in
                print("---> testing link actioned")
                return .systemAction
            })
Raul Pascual
  • 28
  • 1
  • 1
  • 5