I want to fire an action once when using a TapGesture and multiple times when using LongPressGesture. The best example of what I want to do is the "Delete" key on the keyboard, when you long-press it, it continues removing the last character.
My question is how to replicate this behavior in SwiftUI.
For the moment, I came up with this solution (which doesn't work):
struct ContentView: View {
var longPress: some Gesture {
LongPressGesture(minimumDuration: 3)
.onChanged({ (bool) in
guard bool else {
self.timer?.invalidate()
return
}
self.timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { (timer) in
action() // Fired every 0.2 seconds until the user stop pressing
}
})
}
@State var timer: Timer? = nil
var body: some View {
Subview()
.onTapGesture {
action() // Fired once
}
.gesture(longPress)
}
}
You can try the following:
struct ContentView: View {
@State var timer: Timer?
var body: some View {
Text("Tap me")
.onTapGesture {
self.action()
}
.gesture(
LongPressGesture()
.onEnded { _ in // fired when `LongPressGesture` is detected
print("start...")
self.timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { _ in
self.action()
}
}
.sequenced(before:
DragGesture(minimumDistance: 0)
.onEnded { _ in
print("end...")
self.timer?.invalidate()
self.timer = nil
}
)
)
}
func action() {
print("action...")
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.