views:

336

answers:

2

Is there any easy way to detect these kinds of gestures for iPhone? I can use touchesBegan, touchesMoved, touchesEnded. But how can I implement the gestures? thz u.

+1  A: 

You are on the right track. In touchesBegan you should store the position where the user first touches the screen.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];
    self.startPosition = [touch locationInView:self];
}

Similar code in touchesEnded gives you the final position. By comparing the two positions you can determine the direction of movement. If the x-coordinate has moved beyond a certain tolerance you have a left or right swipe.

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject]; 
    CGPoint endPosition = [touch locationInView:self];

    if (startPosition.x < endPosition.x) {
        // Right swipe
    } else {
        // Left swipe
    }
}

You do not need touchesMoved unless you want to detect and track a swipe while the user is still touching the screen. It may also be worth testing that the user has moved a minimal distance before deciding they have performed a swipe.

kharrison
+1  A: 

If you're willing to target iPhone OS 3.2 or later (all iPads or updated iPhones), use the UISwipeGestureRecognizer object. It will do this trivially, which is wickedly cool.

quixoto