I was wondering if there is an easy way to set the minimum length of the swipe, i.e. the length in pixel that the user must scroll so that this gesture is recognized as a swipe.
I noticed that a regular napkin can be completely immune (compared to scrolling through photos in your photo library, for example).
This is the usual way, but I would like to reduce the required scroll length:
- (void)viewDidLoad { // SWIPING GESTURES: UISwipeGestureRecognizer *swipeLeftRecognizer; swipeLeftRecognizer=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(foundLeftSwipe:)]; swipeLeftRecognizer.direction=UISwipeGestureRecognizerDirectionLeft; //swipeRecognizer.numberOfTouchesRequired=1; [self.view addGestureRecognizer:swipeLeftRecognizer]; [swipeLeftRecognizer release]; UISwipeGestureRecognizer *swipeRightRecognizer; swipeRightRecognizer=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(foundRightSwipe:)]; swipeRightRecognizer.direction=UISwipeGestureRecognizerDirectionRight; //swipeRecognizer.numberOfTouchesRequired=1; [self.view addGestureRecognizer:swipeRightRecognizer]; [swipeRightRecognizer release]; [super viewDidLoad]; }
I remember that there is a way to get the starting position of the pixel and the ending position, and then compare them, but it was just interesting if there was a simpler method, i.e. just by defining the value of the minimum swipe length in the code that I have.
EDIT:
Here's how I transcoded it all:
- (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 deltaXX = (gestureStartPoint.x - currentPosition.x); // positive = left, negative = right CGFloat deltaYY = (gestureStartPoint.y - currentPosition.y); // positive = up, negative = down CGFloat deltaX = fabsf(gestureStartPoint.x - currentPosition.x); // will always be positive CGFloat deltaY = fabsf(gestureStartPoint.y - currentPosition.y); // will always be positive if (deltaX >= kMinimumGestureLength && deltaY <= kMaximumVariance) { if (deltaXX > 0) { label.text = @"Horizontal Left swipe detected"; [self performSelector:@selector(eraseText) withObject:nil afterDelay:2]; } else { label.text = @"Horizontal Right swipe detected"; [self performSelector:@selector(eraseText) withObject:nil afterDelay:2]; } } if (deltaY >= kMinimumGestureLength && deltaX <= kMaximumVariance) { if (deltaYY > 0) { label.text = @"Vertical up swipe detected"; [self performSelector:@selector(eraseText) withObject:nil afterDelay:2]; } else { label.text = @"Vertical down swipe detected"; [self performSelector:@selector(eraseText) withObject:nil afterDelay:2]; } } }
source share