Action Trigger when I hold UIButton for 2 second in iPhone

南楼画角 提交于 2019-12-03 11:43:21

问题


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!



来源:https://stackoverflow.com/questions/4815296/action-trigger-when-i-hold-uibutton-for-2-second-in-iphone

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