如何检测“长按”

Posted

技术标签:

【中文标题】如何检测“长按”【英文标题】:How to detect "long tap" 【发布时间】:2020-10-09 18:47:08 【问题描述】:

我有一个UIView 视图,我想在用户按下它然后释放它时执行一些操作。 我在视图中添加了UITapGestureRecognizer,它仅在点击持续时间很短时触发。如果用户触摸视图,等待几秒钟然后抬起手指,什么也不会发生。事件?

UILongPressGestureRecognizer 对我不起作用,因为它会在手指仍然触摸屏幕时触发。

【问题讨论】:

【参考方案1】:

您可以通过跟踪 touchesBegantouchesEnded 的时间来做到这一点:

class LongTapView: UIView 
    
    var touchStart: Date!
    
    var callback: ((Double)->())?
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) 
        touchStart = Date()
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) 
        guard let touchPoint = touches.first?.location(in: self),
              self.bounds.contains(touchPoint) else 
            // touch moved outside of self,
            //  so don't consider it "still pressed"
            touchStart = Date.distantFuture
            return
        
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) 
        guard let touchPoint = touches.first?.location(in: self),
              self.bounds.contains(touchPoint) else 
            // touch was lifted outside of self
            return
        
        let seconds = -(touchStart.timeIntervalSinceNow)
        if seconds < 0.0 
            // this will be the case if touchesMoved outside of self
            //  and then was dragged back in
            return
        
        // tell the controller how long the view was touched
        callback?(seconds)
    

你可以这样使用它:

class TouchTestViewController: UIViewController 
    
    override func viewDidLoad() 
        super.viewDidLoad()
        
        let v = LongTapView()
        v.frame = CGRect(x: 80, y: 120, width: 150, height: 150)
        v.backgroundColor = .red
        view.addSubview(v)
        
        v.callback =  elapsedTime in
            // do what you want here, for example:
            if elapsedTime > 4.0 
                print("View was pressed longer than 4 seconds!")
             else 
                print("View was pressed for only \(elapsedTime) seconds")
            
        
        
    

【讨论】:

以上是关于如何检测“长按”的主要内容,如果未能解决你的问题,请参考以下文章

如何检测“长按”

在 UIScrollView 中检测长按

如何用Arduino检测长按按键的按下和弹起,包括去抖动

AQGridView长按网格单元格检测

如何检测任何视图的长按位置?

检测到长按手势并停止时如何运行功能?