长按手势响应方法为什么被调用了两次

2024-11-21 21:13:31
推荐回答(2个)
回答1:

UILongPressGestureRecognizer *longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
longPressGr.minimumPressDuration = 0.5f;
longPressGr.numberOfTouchesRequired = 1;
[_tableView addGestureRecognizer:longPressGr];
[longPressGr release];

这时会发现每次按住tableView并且松开的时候, longPressAction: 这个方法会执行2次
- (void)longPressAction:(UILongPressGestureRecognizer *)longPress
{
if (longPress.state == UIGestureRecognizerStateBegan) {
CGPoint point = [longPress locationInView:_tableView];

NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:point]; // 可以获取哪个cell上长按
if (indexPath != nil) {
NSLog(@"%ld", indexPath.row);
}

}
}

回答2:

借鉴一下别人的答案 的确可以解决问题:
- (void) handleLongPressAction:(UILongPressGestureRecognizer*)press {
//解决响应两次的问题
if (press.state == UIGestureRecognizerStateEnded) {

return;

} else if (press.state == UIGestureRecognizerStateBegan) {

//TODO
}
}