Last active
June 11, 2024 00:28
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
what's insertRect ? it's not available anywhere, but in your gist