Search code examples
iosuipangesturerecognizeruiswipegesturerecognizer

UISwipeGestureRecognizer @selector is not being called because of UIPanGestureRecognizer set up


In my iOS app I have the following set up:

- (void)setupGestures
{
   UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];                                                           
   [self.view addGestureRecognizer:panRecognizer];

   UISwipeGestureRecognizer* swipeUpRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];

   [swipeUpRecognizer setDirection:UISwipeGestureRecognizerDirectionUp];
   [self.view addGestureRecognizer:swipeUpRecognizer];
}

// then I have following implementation of selectors

// this method supposed to give me the length of the swipe

- (void)panGesture:(UIPanGestureRecognizer *)sender 
{
   if (sender.state == UIGestureRecognizerStateBegan)
   {
      startLocation = [sender locationInView:self.view];
   }
   else if (sender.state == UIGestureRecognizerStateEnded)
   {
      CGPoint stopLocation = [sender locationInView:self.view];
      CGFloat dx = stopLocation.x - startLocation.x;
      CGFloat dy = stopLocation.y - startLocation.y;
      CGFloat distance = sqrt(dx*dx + dy*dy );
      NSLog(@"Distance: %f", distance);
   }
 }

 // this  method does all other actions related to swipes

- (void)handleSwipe:(UISwipeGestureRecognizer *)gestureRecognizer
{
 UISwipeGestureRecognizerDirection direction = [gestureRecognizer direction];
     CGPoint touchLocation = [gestureRecognizer locationInView:playerLayerView];

     if (direction == UISwipeGestureRecognizerDirectionDown && touchLocation.y >  (playerLayerView.frame.size.height * .5))
     {
        if (![toolbar isHidden])
        {
           if (selectedSegmentIndex != UISegmentedControlNoSegment)
           {
              [self dismissBottomPanel];
           }
           else
           {
             [self dismissToolbar];
           }
        }
     }
 }

so the problem is that handleSwipe is never getting called...when I comment out the UIPanGestureRecognizer set up, the handleSwipe starts working.

I'm pretty new to gesture recognition programming, so I'm assuming I'm missing something fundamental here.

Any kind of help is highly appreciated!


Solution

  • You need to tell the gestures how to interact with each other. That can be done by letting them run at the same time (default is that they won't) or by setting one to work only if the other fails.

    To make them both work, make your class the delegate for the gestures and implement

    – gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:

    to return YES.

    To set one to only work if the other fails, use requireGestureRecognizerToFail:.