如何检测iPhone上的左/右滑动?

时间:2010-05-03 11:28:08

标签: objective-c iphone

有没有简单的方法可以为iPhone检测这些类型的手势? 我可以使用touchesBegan,touchesMoved,touchesEnded。但是我该如何实现手势呢?你好。

3 个答案:

答案 0 :(得分:36)

您将使用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");
 }

我认为这是解决问题的更好方法

答案 1 :(得分:21)

你走在正确的轨道上。在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。在决定他们执行滑动之前,用户已经移动了最小距离也是值得测试的。

答案 2 :(得分:15)

如果您愿意定位iPhone OS 3.2或更高版本(所有iPad或更新的iPhone),请使用UISwipeGestureRecognizer对象。它会做得很琐碎,这很酷。