触发TouchDownInside事件,启动一个NStimer.触发TouchUpInside事件,取消定时器.如果用户按住按钮,则定时器调用您的方法执行:定时器延迟将是识别保持所需的时间.
您也可以使用UILongPressGestureRecognizer.
在您的初始化方法(例如viewDidLoad)中,创建一个手势识别器并将其附加到您的按钮:
UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc]
initWithTarget:self
action:@selector(myButtonLongPressed:)];
// you can control how many seconds before the gesture is recognized
gesture.minimumPressDuration = 2;
// attach the gesture to your button
[myButton addGestureRecognizer:gesture];
[gesture release];
Run Code Online (Sandbox Code Playgroud)
事件处理程序myButtonLongPressed:应如下所示:
- (void) myButtonLongPressed:(UILongPressGestureRecognizer *)gesture
{
// Button was long pressed, do something
}
Run Code Online (Sandbox Code Playgroud)
请注意,这UILongPressGestureRecognizer是一个连续事件识别器.当用户仍然按住按钮时,myButtonLongPressed:将被多次调用.如果您只想处理第一个呼叫,可以在myButtonLongPressed:以下位置检查状态:
if (gesture.state == UIGestureRecognizerStateBegan) {
// Button was long pressed, do something
}
Run Code Online (Sandbox Code Playgroud)