How to have a UISwipeGestureRecognizer AND UIPanGestureRecognizer work on the same view

后端 未结 4 1117
春和景丽
春和景丽 2020-12-04 19:58

How would you setup the gesture recognizers so that you could have a UISwipeGestureRecognizer and a UIPanGestureRecognizer work at the same

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 20:24

    Using a pan recognizer to detect swipping and panning:

    - (void)setupRecognizer
    {
        UIPanGestureRecognizer* panSwipeRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanSwipe:)];
        // Here you can customize for example the minimum and maximum number of fingers required
        panSwipeRecognizer.minimumNumberOfTouches = 2;
        [targetView addGestureRecognizer:panSwipeRecognizer];
    }
    
    #define SWIPE_UP_THRESHOLD -1000.0f
    #define SWIPE_DOWN_THRESHOLD 1000.0f
    #define SWIPE_LEFT_THRESHOLD -1000.0f
    #define SWIPE_RIGHT_THRESHOLD 1000.0f
    
    - (void)handlePanSwipe:(UIPanGestureRecognizer*)recognizer
    {
        // Get the translation in the view
        CGPoint t = [recognizer translationInView:recognizer.view];
        [recognizer setTranslation:CGPointZero inView:recognizer.view];
    
        // TODO: Here, you should translate your target view using this translation
        someView.center = CGPointMake(someView.center.x + t.x, someView.center.y + t.y);
    
        // But also, detect the swipe gesture
        if (recognizer.state == UIGestureRecognizerStateEnded)
        {
            CGPoint vel = [recognizer velocityInView:recognizer.view];
    
            if (vel.x < SWIPE_LEFT_THRESHOLD)
            {
                // TODO: Detected a swipe to the left
            }
            else if (vel.x > SWIPE_RIGHT_THRESHOLD)
            {
                // TODO: Detected a swipe to the right
            }
            else if (vel.y < SWIPE_UP_THRESHOLD)
            {
                // TODO: Detected a swipe up
            }
            else if (vel.y > SWIPE_DOWN_THRESHOLD)
            {
                // TODO: Detected a swipe down
            }
            else
            {
                // TODO:
                // Here, the user lifted the finger/fingers but didn't swipe.
                // If you need you can implement a snapping behaviour, where based on the location of your         targetView,
                // you focus back on the targetView or on some next view.
                // It's your call
            }
        }
    }
    

提交回复
热议问题