Skip to content

Instantly share code, notes, and snippets.

@codeactual
Forked from fluidpixel/BetterTapGesture.swift
Created August 12, 2022 13:37
Show Gist options
  • Save codeactual/4c8a8eef8c121ffeb46d0378ec4effa0 to your computer and use it in GitHub Desktop.
Save codeactual/4c8a8eef8c121ffeb46d0378ec4effa0 to your computer and use it in GitHub Desktop.
Using SwiftUI DragGesture as a tap, as TapGesture doesn't give location (as of beta6)
struct ContentView: View {
@State var moved: CGFloat = 0
@State var startTime: Date?
var body: some View {
//0 means that it acts like a press
//coordinateSpace local means local to the view its added to
let tap = DragGesture(minimumDistance: 0, coordinateSpace: .local)
.onChanged { value in
//store distance the touch has moved as a sum of all movements
self.moved += value.translation.width + value.translation.height
//only set the start time if it's the first event
if self.startTime == nil {
//this was being used to determine a quick tap, rather than a long press, but it was since removed
self.startTime = value.time
}
}
.onEnded { tap in
print("tap.translation:", tap)
print("moved:", self.moved)
//if we haven't moved very much, treat it as a tap
// could also check the time difference to determine a tap (ie. <100ms)
if self.moved < 10 && self.moved > -10 {
print("tap.time:", tap.time)
print("startTime:", self.startTime ?? "none")
print("difference:", tap.time.timeIntervalSince(self.startTime ?? Date()))
insertRect(tap.startLocation)
}
self.moved = 0
self.startTime = nil
}
YOURVIEW().gesture(tap)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment