UIButton Long Press Event

Andrea picture Andrea · May 30, 2011 · Viewed 68.7k times · Source

I want to emulate a long a press button, how can I do this? I think a timer is needed. I see UILongPressGestureRecognizer but how can I utilize this type?

Answer

Deepak Danduprolu picture Deepak Danduprolu · May 30, 2011

You can start off by creating and attaching the UILongPressGestureRecognizer instance to the button.

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.button addGestureRecognizer:longPress];
[longPress release];

And then implement the method that handles the gesture

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
         NSLog(@"Long Press");
    }
}

Now this would be the basic approach. You can also set the minimum duration of the press and how much error is tolerable. And also note that the method is called few times if you after recognizing the gesture so if you want to do something at the end of it, you will have to check its state and handle it.