How to programmatically complete / reset UIGestureRecognizer?

Say I'm tracking a drag gesture right now. In my event handler, I use a threshold to determine when a drag and drop results in an action. When the threshold is crossed, I want to indicate that the drag gesture is complete.

The only thing I can find in the docs is the line here :

If you change this property to NO while the gesture recognizer is currently recognizing a gesture, the gesture recognizer transitions to the canceled state.

So:

if (translation.y > 100) { // do action [self doAction]; //end recognizer sender.enabled = NO; sender.enabled = YES; } 

This works, but it looks like there might be a more neat way.

Does anyone know of another way to indicate that the gesture ended programmatically? I would expect something like the -end: method, which will generate a final event with a state of UIGestureRecognizerStateEnded .

+8
ios uigesturerecognizer gesture
source share
2 answers

Have you created a custom UIGestureRecognizer? If the gesture you recognize is different from the standard ones defined by Apple because it has a different threshold or otherwise does not match the usual UIPanGestureRecognizer, then it may make sense to create your own UIGestureRecognizer. ( see notes to subclass )

If you have subclasses of UIGestureRecognizer, you can simply set the state as follows:

  self.state = UIGestureRecognizerStateEnded; 

You probably want to do this in the touch: Moved: withEvent: methods. Also note:

"Subclasses of UIGestureRecognizer must import UIGestureRecognizerSubclass.h. This header file contains a state override that makes it read-write.

On the other hand, if you are only implementing UIGestureRecognizerDelegate, the state is read-only and there is no way to set it directly. In this case, your disconnect / enable method may be the best you can do.

+7
source share

With the code that you showed, you need to have logic to start the animation when the gesture recognizer is canceled, and I would say that this is not so good, because there are other ways in which this gesture recognizer can be canceled without wanting to make the animation.

Given that you have a way to start the animation, you just need to call this method when the threshold is passed and when the gesture ends normally. Then two different cases. The code you submit will look like this:

 if (translation.y > 100) { // do action [self finishFlip]; sender.enabled = NO; sender.enabled = YES; } 

Undoing gestures here can also be useful if it prevents any of the following actions if the user continues to drag his finger.

If you have a team developing on this subject, and you need a specific event, you should subclass the gesture recognizer, as suggested by nont.

+3
source share

All Articles