How to recognize swipe in all 4 directions?

前端 未结 8 471
后悔当初
后悔当初 2020-12-03 01:00

I need to recognize swipes in all directions (Up/Down/Left/Right). Not simultaneously, but I need to recognize them.

I tried:

  UISw         


        
8条回答
  •  星月不相逢
    2020-12-03 01:58

    I finally found the simplest answer, please mark this as the answer if you agree.

    If you only have one direction swipe + pan, you just say: [myPanRecogznier requireGestureRecognizerToFail:mySwipeRecognizer];

    But if you have two or more swipes, you can't pass an array into that method. For that, there's UIGestureRecognizerDelegate that you need to implement.

    For example, if you want to recognize 2 swipes (left and right) and you also want to allow the user to pan up, you define the gesture recognizers as properties or instance variables, and then you set your VC as the delegate on the pan gesture recognizer:

    _swipeLeft = [[UISwipeGestureRecognizer alloc] ...]; // use proper init here
    _swipeRight = [[UISwipeGestureRecognizer alloc] ...]; // user proper init here
    _swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    _swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    _pan = [[UIPanGestureRecognizer alloc] ...]; // use proper init here
    
    _pan.delegate = self;
    
    // then add recognizers to your view
    

    You then implement - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer delegate method, like so:

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
    {
        if (gestureRecognizer == _pan && (otherGestureRecognizer == _swipeLeft || otherGestureRecognizer == _swipeRight)) {
            return YES;
        }
    
        return NO;
    }
    

    This tells the pan gesture recognizer to only work if both left and right swipes fail to be recognize - perfect!

    Hopefully in the future Apple will just let us pass an array to the requireGestureRecognizerToFail: method.

提交回复
热议问题