'SwiftUI: use Link with onTapGesture
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?
Solution 1:[1]
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
})
Solution 2:[2]
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
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Z S |
Solution 2 | Raul Pascual |