Question

Simple question here: How can I detect when I user swipes their finger on the screen of the iPhone?

Was it helpful?

Solution

You need to implement a gesture recognizer in your application.

In your interface:

#define kMinimumGestureLength  30
#define kMaximumVariance   5
#import <UIKit/UIKit.h>
@interface *yourView* : UIViewController {
    CGPoint gestureStartPoint;
}
@end

kMinimumGestureLength is the minimum distance the finger as to travel before it counts as a swipe. kMaximumVariance is the maximum distance, in pixels, that the finger can end above the beginning point on the y-axis.

Now open your interface .xib file and select your view in IB, and make sure Multiple Touch is enabled in View Attributes.

In your implementation, implement these methods.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        gestureStartPoint = [touch locationInView:self.view];
  }

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self.view];    

    CGFloat deltaX = fabsf(gestureStartPoint.x - currentPosition.x);
    CGFloat deltaY = fabsf(gestureStartPoint.y - currentPosition.y);


  if(deltaX >= kMinimumGestureLength && deltaY <= kMaximumVariance){
      //do something 
 }
else if(deltaY >= kMinimumGestureLength && deltaX <= kMaximumVariance){
      //do something
   }
 }

This is one way to implement a swipe recognizer. Also, you really should check out the Docs on this topic:

UISwipeGestureRecognizer

OTHER TIPS

The UIGestureRecognizer is what you want. Especially the UISwipeGestureRecognizer subclass

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top