UILongPressGestureRecognizer will not respond to touch & HOLD

I am writing an Objective-C program for the iPhone.

I am trying to implement a UILongPressGestureRecognizer and cannot make it behave the way I want.

What I want to do is simply:

Respond to the touch that is held on the screen.

UILongPressGestureRecognizer works great every time I touch it and when I touch it, but if I keep the touch in the same place, nothing happens.

Why?

How can I handle the touch without moving and stay in the same place?

Here is my current code.


 // Configure the press and hold gesture recognizer touchAndHoldRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(touchAndHold:)]; touchAndHoldRecognizer.minimumPressDuration = 0.1; touchAndHoldRecognizer.allowableMovement = 600; [self.view addGestureRecognizer:touchAndHoldRecognizer]; 
+7
source share
1 answer

The behavior that you describe when your gesture recognizer does not receive further calls from your handler when you are not moving is standard behavior. The state property for these gestures when moving is of type UIGestureRecognizerStateChanged , so it makes sense that if things have not changed, your handler will not be called.

You could

  • After calling your gesture recognizer with state of UIGestureRecognizerStateBegan start a second timer;
  • After calling your gesture recognizer with state UIGestureRecognizerStateCancelled , UIGestureRecognizerStateFailed or UIGestureRecognizerStateEnded then invalidate and release the timer;
  • Make sure that the gesture recognition method stores any value you are looking for in some property of the class (for example, locationInView value or something else)

So maybe something like:

 @interface ViewController () @property (nonatomic) CGPoint location; @property (nonatomic, strong) NSTimer *timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]; gesture.minimumPressDuration = 0.1; gesture.allowableMovement = 600; [self.view addGestureRecognizer:gesture]; } - (void)handleTimer:(NSTimer *)timer { [self someMethod:self.location]; } - (void)handleGesture:(UIGestureRecognizer *)gesture { self.location = [gesture locationInView:self.view]; if (gesture.state == UIGestureRecognizerStateBegan) { self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES]; } else if (gesture.state == UIGestureRecognizerStateCancelled || gesture.state == UIGestureRecognizerStateFailed || gesture.state == UIGestureRecognizerStateEnded) { [self.timer invalidate]; self.timer = nil; } [self someMethod:self.location]; } - (void)someMethod:(CGPoint)location { // move whatever you wanted to do in the gesture handler here. NSLog(@"%s", __FUNCTION__); } @end 
+12
source

All Articles