Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action Trigger when I hold UIButton for 2 second in iPhone

I have a UIButton in my application and an action which is triggered when I TouchDown UIButton.

Is it possible to detect a Touch-and-Hold on the UIButton on the iPhone? I want my action to trigger when the user holds the button for 2 seconds or more.

Any Ideas?

like image 851
Siddiqui Avatar asked Jan 27 '11 10:01

Siddiqui


2 Answers

UILongPressGestureRecognizer is what you need. For example,

UILongPressGestureRecognizer *longPress_gr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(doAction:)];
[longPress_gr setMinimumPressDuration:2]; // triggers the action after 2 seconds of press
[yourButton addGestureRecognizer:longPress_gr];

To let your action get triggered only once(ie., when the 2 seconds duration is over), make sure you have your doAction: method looks something like this,

- (void)doAction:(UILongPressGestureRecognizer *)recognizer {

    if (recognizer.state == UIGestureRecognizerStateBegan) {

        // Your code here
    }
}
like image 154
EmptyStack Avatar answered Oct 31 '22 08:10

EmptyStack


On the other way you can use this NBTouchAndHoldButton. This is exactly what you want, and it is very easy to implement it:

TouchAndHoldButton * pageDownButton = [TouchAndHoldButton buttonWithType:UIButtonTypeCustom];
[pageDownButton addTarget:self action:@selector(pageDownAction:) forTouchAndHoldControlEventWithTimeInterval:0.2];

Good luck!

like image 42
Balazs Nemeth Avatar answered Oct 31 '22 10:10

Balazs Nemeth