Search code examples
ioscocoa-touchcocoatouchesbegan

pressGestureRecognizer and touchesBegan


I have the following problem. I am using a UILongPressGestureRecognizer to put a UIView into a "toggle mode". If the UIView is in "toggle mode" the user is able to drag the UIView around the screen. For dragging the UIView around the screen I am using the methods touchesBegan, touchesMoved and touchesEnded.

It works, but: I have to lift my finger in order to drag it, because the touchesBegan method got already called and therefore is not called again and therefore I can't drag the UIView around the screen.

Is there any way to manually call touchesBegan after UILongPressGestureRecognizer got triggered (UILongPressGestureRecognizer changes a BOOL value and the touchesBegan only works if this BOOL is set to YES).


Solution

  • UILongPressGestureRecognizer is a continuous gesture recognizer, so rather than resorting to touchesMoved or UIPanGestureRecognizer, just check for UIGestureRecognizerStateChanged, e.g.:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
        [self.view addGestureRecognizer:gesture];
    }
    
    - (void)handleGesture:(UILongPressGestureRecognizer *)gesture
    {
        CGPoint location = [gesture locationInView:gesture.view];
    
        if (gesture.state == UIGestureRecognizerStateBegan)
        {
            // user held down their finger on the screen
    
            // gesture started, entering the "toggle mode"
        }
        else if (gesture.state == UIGestureRecognizerStateChanged)
        {
            // user did not lift finger, but now proceeded to move finger
    
            // do here whatever you wanted to do in the touchesMoved
        }
        else if (gesture.state == UIGestureRecognizerStateEnded)
        {
            // user lifted their finger
    
            // all done, leaving the "toggle mode"
        }
    }