ICL1901
ICL1901

Reputation: 7778

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

Upvotes: 2

Views: 4449

Answers (3)

Sandeep Jangir
Sandeep Jangir

Reputation: 412

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

}

Upvotes: 3

Pankaj Wadhwa
Pankaj Wadhwa

Reputation: 3063

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

Upvotes: 1

Philip
Philip

Reputation: 666

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
}

Upvotes: 7

Related Questions