检测UITableView单元格中的Tap&Hold

我们如何检测一个UITableViewCell按住?

在iOS 3.2或更高版本中,您可以使用UILongPressGestureRecognizer

这是从我的应用程序直接提起的代码。 您应该将这些方法(和一个布尔_cancelTouches成员)添加到您从UITableViewCell派生的类。

 -(void) tapNHoldFired { self->_cancelTouches = YES; // DO WHATEVER YOU LIKE HERE!!! } -(void) cancelTapNHold { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tapNHoldFired) object:nil]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self->_cancelTouches = NO; [super touchesBegan:touches withEvent:event]; [self performSelector:@selector(tapNHoldFired) withObject:nil afterDelay:.7]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [self cancelTapNHold]; if (self->_cancelTouches) return; [super touchesEnded:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ [self cancelTapNHold]; [super touchesMoved:touches withEvent:event]; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { [self cancelTapNHold]; [super touchesCancelled:touches withEvent:event]; } 
 //Add gesture to a method where the view is being created. In this example long tap is added to tile (a subclass of UIView): // Add long tap for the main tiles UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTap:)]; [tile addGestureRecognizer:longPressGesture]; [longPressGesture release]; -(void) longTap:(UILongPressGestureRecognizer *)gestureRecognizer{ NSLog(@"gestureRecognizer= %@",gestureRecognizer); if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) { NSLog(@"longTap began"); } } 

您可能应该处理UIControlTouchDown事件,根据“hold”的含义,触发一个NSTimer,该触发器会在触发后计算间隔,并在触发或释放触摸( UIControlTouchUpInsideUIControlTouchUpOutside事件)时失效。 当定时器启动时,您会检测到您的“轻触并按住”。