如何检测UISwipeGestureRecognizer的结束?

来自Apple文档

滑动是离散手势,因此每个手势仅发送一次相关联的动作消息。

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event 

当我使用UISwipeGestureRecognizer时也不会调用它

如何检测用户何时抬起手指?

我想通了,实际上这很简单,而不是使用UISwipeGestureRecognizer来检测我自己使用事件处理检测到的滑动

 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; self.initialPosition = [touch locationInView:self.view]; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; CGPoint movingPoint = [touch locationInView:self.view]; CGFloat moveAmt = movingPoint.y - self.initialPosition.y; if (moveAmt < -(minimum_detect_distance)) { [self handleSwipeUp]; } else if (moveAmt > minimum_detect_distance) { [self handleSwipeDown]; } } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ [self reset]; } -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{ [self reset]; } 

我没有子类化UIGestureRecognizer但只在所需的视图控制器中进行事件处理,因为在重置方法中我重置了属于视图控制器的少量变量,计数器和计时器。

我认为你需要更好地检查手势识别器的状态属性:

 - (void)swipe:(UISwipeGestureRecognizer *)recognizer { CGPoint point = [recognizer locationInView:[recognizer view]]; if (recognizer.state == UIGestureRecognizerStateBegan) NSLog(@"Swipe began"); else if (recognizer.state == UIGestureRecognizerStateEnded) NSLog(@"Swipe ended"); } 

Apple文档说,UISwipeGestureRecognizer是一个离散手势,所以你需要使用连续手势,在这种情况下使用UIPanGestureRecognizer。

这是代码:

 - (void)viewDidLoad{ [super viewDidLoad]; // add pan recognizer to the view when initialized UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panRecognized:)]; [panRecognizer setDelegate:self]; [yourView addGestureRecognizer:panRecognizer]; // add to the view you want to detect swipe on } -(void)panRecognized:(UIPanGestureRecognizer *)sender{ CGPoint distance = [sender translationInView: yourView]; if (sender.state == UIGestureRecognizerStateEnded) { [sender cancelsTouchesInView]; if (distance.x > 70 && distance.y > -50 && distance.y < 50) { // right NSLog(@"user swiped right"); NSLog(@"distance.x - %f", distance.x); } else if (distance.x < -70 && distance.y > -50 && distance.y < 50) { //left NSLog(@"user swiped left"); NSLog(@"distance.x - %f", distance.x); } if (distance.y > 0) { // down NSLog(@"user swiped down"); NSLog(@"distance.y - %f", distance.y); } else if (distance.y < 0) { //up NSLog(@"user swiped up"); NSLog(@"distance.y - %f", distance.y); } } } 

不要忘记添加UIGestureRecognizerDelegate。