Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - GestureRecognizer sometimes doesn't fire?

I am trying to get a long key press on a button working in objective c for iPhone.

Here is the code I have put together for the GestureRecognizer:

    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    longPressGesture.minimumPressDuration = 1.0; //1 second
    longPressGesture.delegate = self;
    [deleteButton addGestureRecognizer:longPressGesture];
    [longPressGesture release];

And here is the function that I use in the selector to call when a long key press is detected.

-(void)handleLongPress:(UILongPressGestureRecognizer *) gestureRecognizer
{
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"Got handle long key press");
        NumLabel.text = @"";

    }

}

I have also added the following functions as part of my delegate class but they don't seem to have had any impact:

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{

    return YES;
}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{

    return NO;

}

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{

    return YES;

}

My issue is that this sometimes works but then again sometimes it doesn't, most of the time I get the call to handleLongPress and it works fine but every so often when the button is pressed and held down I get nothing until I lift my finger off the button at which stage my normal code for the button is run.

Have I missed something in the tutorials or can anyone spot why it would work sometimes but I get nothing on other occasions?

EDIT

I actually think the issue is with the way the button is pressed, if I press the button straight on and hold it then it works fine, however if my finger slips on the button even a little bit then the handleLongPress function isn't called.

I'm assuming this is because it recognizes it as a separate gesture? Is there a way to make sure that handleLongPress gets called as long as the button is held down even if the finger moves across the button at all?

like image 584
Donal Rafferty Avatar asked Mar 08 '26 05:03

Donal Rafferty


1 Answers

Gesture recognizers are only for TOUCHES, not for button states. A Long press is really just pressing and releasing. When the touch moves, the gesture will be canceled!!
If you just want to know if your button is pressed more than a specific time, you can handle TouchDown/TouchCancel events of your button and add some timing.

like image 189
Martin Ullrich Avatar answered Mar 10 '26 20:03

Martin Ullrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!