Action Trigger when I hold UIButton for 2 second in iPhone

有些话、适合烂在心里 提交于 2019-12-03 03:11:13

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

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!