[英]SwiftUI: How to run action when user releases screen from a longPressGesture?
[英]Use LongPressGesture to fire an action multiple time
我想在使用 TapGesture 時觸發一次動作,在使用 LongPressGesture 時觸發多次。 我想做的最好的例子是鍵盤上的“刪除”鍵,當你長按它時,它會繼續刪除最后一個字符。
我的問題是如何在 SwiftUI 中復制此行為。
目前,我想出了這個解決方案(不起作用):
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)
}
}
您可以嘗試以下操作:
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...")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.