Search code examples
iosobjective-ccocoa-touchswipe

How to detect swipe direction?


I would like to detect when a user makes a swipe gesture, and detect it's direction (left, right, up or down). I need to detect it not when the gesture is finished, but just when the iPhone knows the direction, even if it's not finished.

I am using XCode 5, and designing for iPhone 5 with iOS 7.

I would like to know the code that I have to paste to the .h, and to the .m, and if I have to drag and drop any item to the mainView.


Solution

  • If you want to know the direction when the gesture is not finished you would probably need the UIPanGestureRecognizer and detect the direction using the velocityInView: method.

    in the *.h file:

    @interface ViewController : UIViewController
    
    @property (nonatomic, strong) UIPanGestureRecognizer *recognizer;
    
    @end
    

    in the *.m file:

    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        self.recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
    
        [self.view addGestureRecognizer:self.recognizer];
    }
    
    -(void)panGesture:(UIPanGestureRecognizer *)sender
    {
        NSLog(@"Velocity: %@", NSStringFromCGPoint([sender velocityInView:self.view]));
    
        // Here You need to determine the direction
    }
    @end