如何使用UISwipeGestureRecognizer检测UITableViewCell中的滑动事件
我有一个UITableViewCell类,我想检测滑动事件(删除),以便隐藏drawRect
绘制的一些graphics
首先,我给这个单元添加了一个UISwipeGestureRecognice
:
// Init swipe gesture recognizer self.swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeCell:)]; self.swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight; self.swipeRecognizer.delegate = self; [self.contentView addGestureRecognizer:self.swipeRecognizer];
比我实施了一个方法来对滑动事件作出反应:
- (void)swipeCell:(UISwipeGestureRecognizer *)recognizer { switch (recognizer.state) { case UIGestureRecognizerStateBegan: self.swipeStartPoint = [recognizer locationInView:self.backgroundView]; BaseLogDebug(INFO, @"Swipe Began at %@", NSStringFromCGPoint(self.swipeStartPoint)); break; case UIGestureRecognizerStateChanged: { CGPoint currentPoint = [recognizer locationInView:self.backgroundView]; CGFloat deltaX = currentPoint.x - self.swipeStartPoint.x; BaseLogDebug(INFO, @"Swipe Moved %f", deltaX); } break; case UIGestureRecognizerStateEnded: BaseLogDebug(INFO, @"Swipe Ended"); break; case UIGestureRecognizerStateCancelled: BaseLogDebug(INFO, @"Swipe Cancelled"); break; default: break; } }
为了允许同时使用手势识别器,我实现了以下方法:
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; }
手势识别的唯一状态是状态UIGestureRecognizerStateEnded
。 我的代码有什么问题?
从UIGestureRecognizer类参考文档 :
离散手势识别器从UIGestureRecognizerStatePossible转换到UIGestureRecognizerStateFailed或UIGestureRecognizerStateRecognized。
和
手势识别器识别一个离散的事件,如点击或滑动,但不报告手势内的变化。 换句话说,离散手势不会通过“开始”和“已更改”状态进行转换,它们也不会失败或被取消。
UISwipeGestureRecognizer
是一个离散的手势。 如果你想要一个连续的(但相似的)手势,请改用UIPanGestureRecognizer
。