Skip to content

Instantly share code, notes, and snippets.

@fluidpixel
Last active June 11, 2024 00:28
Show Gist options
  • Save fluidpixel/fe1fce8c1e78f91fe4e239b3e14d21e1 to your computer and use it in GitHub Desktop.
Save fluidpixel/fe1fce8c1e78f91fe4e239b3e14d21e1 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)
}
}
@iMostfa
Copy link

iMostfa commented Aug 25, 2020

what's insertRect ? it's not available anywhere, but in your gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment