Action Trigger when I hold UIButton for 2 second i

2020-05-26 07:35发布

问题:

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?

回答1:

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


回答2:

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!