How can I capture which direction is being panned using UIPanGestureRecognizer?

后端 未结 3 1766
暖寄归人
暖寄归人 2021-01-29 20:43

Ok so I have been looking around at just about every option under the sun for capturing multi-touch gestures, and I have finally come full circle and am back at the UIPanGesture

3条回答
  •  再見小時候
    2021-01-29 21:05

    On UIPanGestureRecognizer you can use -velocityInView: to get the velocity of the fingers at the time that gesture was recognised.

    If you wanted to do one thing on a pan right and one thing on a pan left, for example, you could do something like:

    - (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer
    {
        CGPoint velocity = [gestureRecognizer velocityInView:yourView];
    
        if(velocity.x > 0)
        {
            NSLog(@"gesture went right");
        }
        else
        {
            NSLog(@"gesture went left");
        }
    }
    

    If you literally want to detect a reversal, as in you want to compare a new velocity to an old one and see if it is just in the opposite direction — whichever direction that may be — you could do:

    // assuming lastGestureVelocity is a class variable...
    
    - (void)handleGesture:(UIPanGestureRecognizer *)gestureRecognizer
    {
        CGPoint velocity = [gestureRecognizer velocityInView:yourView];
    
        if(velocity.x*lastGestureVelocity.x + velocity.y*lastGestureVelocity.y > 0)
        {
            NSLog(@"gesture went in the same direction");
        }
        else
        {
            NSLog(@"gesture went in the opposite direction");
        }
    
        lastGestureVelocity = velocity;
    }
    

    The multiply and add thing may look a little odd. It's actually a dot product, but rest assured it'll be a positive number if the gestures are in the same direction, going down to 0 if they're exactly at right angles and then becoming a negative number if they're in the opposite direction.

提交回复
热议问题