Search code examples
iosuiviewuikituipangesturerecognizer

UIPanGestureRecognizer detect non-movement/stillness


I am using UIPanGestureRecognizer to track movement of finger. The user may pan quite fast initially but then may hold on to a point on the screen for few seconds or so without releasing the finger. I want to detect when such a premature 'end of dragging' event. I tried detecting this using velocity but it is not always reliable.

       let location = panGesture.location(in: selectedCell.superview)
        
        let velocity = panGesture.velocity(in: selectedCell.superview)
        NSLog("Velocity, \(velocity)")
        
        switch panGesture.state {
        case .began:
            break
            
        case .changed:
            let delta = panGesture.translation(in: self)
            
            if velocity.x <= 0.05 && velocity.y <= 0.05 {
                NSLog("Velocity 0!!!!")
            }
            panGesture.setTranslation(.zero, in: self)
            break

Solution

  • If user is not moving the finger at all, the event won't be fired. Here's a workaround -

    Once you know that the gesture.state == .began, Add a timer to fire every 0.1s to check what is translation since last known point.

    Even if user holds still, you will be able to check the translation and hence the velocity every 0.1s reliably.

    Do not forget to call timer.invalidate() in .cancelled, .ended & .failed states.