Search code examples
xcodeuisegmentedcontrolselectedgestures

Xcode/ ios5 - Long Touch gesture called twice


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....?


Solution

  • 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
    }