UILongPressGestureRecognizer not getting called for multiple UIButtons

Wed, 02/01/2012 - 15:01 -- jeff

UILongPressGestureRecognizer not getting called for multiple UIButtons? Try allocated a new UILongPressGestureRecognizer for each button!

Note, the following code is using ARC.

    UILongPressGestureRecognizer *longPress = 
        [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler:)];
    
    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler:)];
    [imageButton1 addGestureRecognizer:longPress];
    longPress = nil;

    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler:)];
    [imageButton2 addGestureRecognizer:longPress];
    longPress = nil;
    
    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler:)];
    [imageButton3 addGestureRecognizer:longPress];
    longPress = nil;

And here is my code for the selector method, in case you're curious:

// long press gesture for resetting images
- (void)longPressHandler:(UILongPressGestureRecognizer*)sender { 
    if (sender.view == imageButton1){
        NSLog(@"OK!");
    }
    
    if (sender.state == UIGestureRecognizerStateEnded) {
        NSLog(@"Long press Ended");
        // delete the image here
    }
    else {
        NSLog(@"Long press detected.");
    }
}

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.