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.
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.
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.
You will using UISwipeGestureRecognizer Object to detect the Touch and direction of Swipe In
UIView or anywhere in iphone sdk.
UISwipeGestureRecognizer *rightRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(rightSwipeHandle:)];
rightRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[rightRecognizer setNumberOfTouchesRequired:1];
//add the your gestureRecognizer , where to detect the touch..
[view1 addGestureRecognizer:rightRecognizer];
[rightRecognizer release];
UISwipeGestureRecognizer *leftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(leftSwipeHandle:)];
leftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[leftRecognizer setNumberOfTouchesRequired:1];
[view1 addGestureRecognizer:leftRecognizer];
[leftRecognizer release];
- (void)rightSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(@"rightSwipeHandle");
}
- (void)leftSwipeHandle:(UISwipeGestureRecognizer*)gestureRecognizer
{
NSLog(@"leftSwipeHandle");
}
I think this the Better solution for your problem