简体   繁体   English

使用 LongPressGesture 多次触发一个动作

[英]Use LongPressGesture to fire an action multiple time

I want to fire an action once when using a TapGesture and multiple times when using LongPressGesture.我想在使用 TapGesture 时触发一次动作,在使用 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.我的问题是如何在 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...")
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM