有没有简单的方法来检测iPhone的这些手势?我可以使用touchesBegan,touchesMoved,touchesEnded.但是我该如何实现手势呢?你.
您将使用UISwipeGestureRecognizer对象来检测触摸和触摸方向
UIView或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"); }
我认为这是解决问题的更好方案
你走在正确的轨道上.在touchesBegan中,您应该存储用户首次触摸屏幕的位置.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; self.startPosition = [touch locationInView:self]; }
touchesEnded中的类似代码为您提供最终位置.通过比较两个位置,您可以确定移动方向.如果x坐标移动超过某个公差,则可以向左或向右滑动.
- (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 } }
除非您想在用户仍在触摸屏幕时检测并跟踪滑动,否则您不需要touchesMoved.在决定他们已经执行滑动之前,用户已经移动了最小距离也是值得测试的.
如果您愿意定位iPhone OS 3.2或更高版本(所有iPad或更新的iPhone),请使用该UISwipeGestureRecognizer
对象.它会做到这一点,这是非常酷的.