2

I have a segmented control that allows both short and long gestures. The short gesture recognition is fine. The long gesture method is being called twice. I am scratching my head as to why.

This is part of the code to build a color toolbar:

UILongPressGestureRecognizer* longPressGestureRec =
    [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPressGestureRec.minimumPressDuration = 1.5;
    //longPressGestureRec.cancelsTouchesInView = NO;
    [colorControl addGestureRecognizer:longPressGestureRec];

This is part of the longPress method:

-(void) longPress:(id)sender {
    NSLog(@"%s", __FUNCTION__);     
    switch (colorIndex) {
        case 0:
            [self showMoreWhiteColors:(id)sender];
            break;

        case 1:
            [self showMoreRedColors:(id)sender];
            break;

By looking at the log, I can see that the longPress method is called twice every time I hold the button.

Any ideas what I'm doing wrong, missing, not doing....?

ICL1901
  • 7,632
  • 14
  • 90
  • 138
  • 2
    Answered here: http://stackoverflow.com/questions/3319591/uilongpressgesturerecognizer-gets-called-twice-when-pressing-down – Philip Apr 26 '12 at 23:48
  • Hi Phillip. Thanks for responding. I saw that post. There seem to be several conflicting answers there. What would you suggest? – ICL1901 Apr 27 '12 at 01:27

3 Answers3

7

I just check if the state is anything but UIGestureRecognizerStateBegan and return otherwise prior to executing the code I want to. So:

-(void) longPressGesture:(UIGestureRecognizer*)gesture
{
    if ( gesture.state != UIGestureRecognizerStateBegan )
       return; // discard everything else

   // do something in response to long gesture
}
Philip
  • 655
  • 8
  • 12
3
- (void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
if(UIGestureRecognizerStateBegan == gesture.state) {
    // Called on start of gesture, do work here
}

if(UIGestureRecognizerStateChanged == gesture.state) {
    // Do repeated work here (repeats continuously) while finger is down
}

if(UIGestureRecognizerStateEnded == gesture.state) {
    // Do end work here when finger is lifted
}

}

Sandeep Jangir
  • 412
  • 5
  • 14
1

Or you can do this way.

-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture {
      switch(gesture.state){
       case UIGestureRecognizerStateBegan:

            // Do your stuff here.
            NSLog(@"State Began");
            break;
       case UIGestureRecognizerStateChanged:
            NSLog(@"State changed");
            break;
       case UIGestureRecognizerStateEnd:
            NSLog(@"State End");
            break;
       default:
            break;
      }
}
Pankaj Wadhwa
  • 3,073
  • 3
  • 28
  • 37