Skip to content

Instantly share code, notes, and snippets.

@epaga
Last active December 13, 2021 17:57
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epaga/96abcc458e24d688de7e315c4300a711 to your computer and use it in GitHub Desktop.
Save epaga/96abcc458e24d688de7e315c4300a711 to your computer and use it in GitHub Desktop.
SwiftUI View for getting taps with(!) the tap locations unlike the current tapAction and tapGestures of SwiftUI
// SwiftUI View for getting taps with(!) the tap locations unlike the current tapAction and tapGestures of SwiftUI
// There may be a way easier way to do this, not sure...
/*
Use like so:
TappableView {
(location, taps) in
if taps == 1 {
print("single tap at \(location)")
} else if taps == 2 {
print("double tap at \(location)")
}
}
*/
struct TappableView:UIViewRepresentable {
var tappedCallback: ((CGPoint, Int) -> Void)
func makeUIView(context: UIViewRepresentableContext<TappableView>) -> UIView {
let v = UIView(frame: .zero)
let gesture = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.tapped))
gesture.numberOfTapsRequired = 1
let gesture2 = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.doubleTapped))
gesture2.numberOfTapsRequired = 2
gesture.require(toFail: gesture2)
v.addGestureRecognizer(gesture)
v.addGestureRecognizer(gesture2)
return v
}
class Coordinator: NSObject {
var tappedCallback: ((CGPoint, Int) -> Void)
init(tappedCallback: @escaping ((CGPoint, Int) -> Void)) {
self.tappedCallback = tappedCallback
}
@objc func tapped(gesture:UITapGestureRecognizer) {
let point = gesture.location(in: gesture.view)
self.tappedCallback(point, 1)
}
@objc func doubleTapped(gesture:UITapGestureRecognizer) {
let point = gesture.location(in: gesture.view)
self.tappedCallback(point, 2)
}
}
func makeCoordinator() -> TappableView.Coordinator {
return Coordinator(tappedCallback:self.tappedCallback)
}
func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<TappableView>) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment