AOY AOY - 4 months ago 28
iOS Question

Why is UIPanGestureRecognizer firing with UIGestureRecognizerStateEnded multiple times?

What I want to achieve is just to draw a line between the point where the user started the gesture and the point where he ended doing this. I thought that UIGestureRecognizerStateEnded is the state which I need but it is called multiple times. I would be really grateful if anyone could explain me why is this happening and how to catch the last point.

- (void)drawingViewDidPan:(UIPanGestureRecognizer*)sender
{
CGPoint currentDraggingPosition = [sender locationInView:_drawingView];

if(sender.state == UIGestureRecognizerStateBegan){
_prevDraggingPosition = currentDraggingPosition;
NSLog(@"---");
}

if(sender.state != UIGestureRecognizerStateEnded){
[self drawLine:_prevDraggingPosition to:currentDraggingPosition];
NSLog(@"???");
}
_prevDraggingPosition = currentDraggingPosition;
}


the log:


2016-08-05 17:14:46.086 X[2518:356899] ---
2016-08-05 17:14:46.092 X[2518:356899] ???
2016-08-05 17:14:46.127 X[2518:356899] ???
2016-08-05 17:14:46.153 X[2518:356899] ???
2016-08-05 17:14:46.177 X[2518:356899] ???
2016-08-05 17:14:46.205 X[2518:356899] ???
2016-08-05 17:14:46.226 X[2518:356899] ???
2016-08-05 17:14:46.246 X[2518:356899] ???
2016-08-05 17:14:46.279 X[2518:356899] ???
...

Answer
if(sender.state != UIGestureRecognizerStateEnded){
    [self drawLine:_prevDraggingPosition to:currentDraggingPosition];
     NSLog(@"???");
}

sender.state != UIGestureRecognizerStateEnded will evaluate successfully for each type of Gesture state except the UIGestureRecognizerStateEnded one.

Change != to == and it will work properly.