6

I have an UILongPressGestureRecognizer attached to the controller's view. I want to freeze some timers until user holds his finger. The problem is I can't determine when the touch event is ended. Maybe I should use observer on the gesture recognizer's property state? Or there are other ways to do this?

Brief

On the controller's view a UIScrollView (which implements a paged gallery) is placed, pages can be switched by dragging (swiping). Also there is an UITapGestureRecognizer, also attached to the controller's view, which handles some other tasks.

efpies
  • 3,625
  • 6
  • 34
  • 45

1 Answers1

26

Yes you can accomplish this by looking at the recognizer's state, but you don't need to use an observer. You should declare an action method in your gesture recognizer's delegate that will be called when the recognizer fires. The method will then automatically be called whenever the recognizer's state changes.

You need to look for the state UIGestureRecognizerStateBegan to begin your timer, and you need to look for the states UIGestureRecognizerStateEnded, UIGestureRecognizerStateFailed, and UIGestureRecognizerStateCancelled to pause your timer.

Simply connect up your gesture with the action in Interface Builder.

-(IBAction)longPressBegan:(UILongPressGestureRecognizer *)recognizer
{
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        // Long press detected, start the timer
    }
    else
    {
        if (recognizer.state == UIGestureRecognizerStateCancelled
            || recognizer.state == UIGestureRecognizerStateFailed
            || recognizer.state == UIGestureRecognizerStateEnded)
        {
            // Long press ended, stop the timer
        }
    }
}
petemorris
  • 516
  • 4
  • 4
  • Exactly what I needed. I din't know that `UILongPressGestureRecognizer` calls `action` twice: on the begin and on the end. – efpies Jan 17 '13 at 10:58
  • Yes, but not just beginning and end. It invokes the action method every time its state is updated. So, for example, if the user moves a finger in the middle of a long press, the method will be called with the state UIGestureRecognizerStateChanged. We use a switch or if statement to handle the states we're interested in, and ignore the rest. – petemorris Jan 17 '13 at 11:44
  • What `if (recognizer.state == UIGestureRecognizerStateChanged)`? In my case, I have it together with `UIGestureRecognizerStateBegan`, because it is used when the user moves his finger without lifting it (i.e. if he wants to move the finger out of the way, to see what is underneath it...) – Gik Feb 17 '18 at 18:24