繁体   English   中英

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

[英]How to detect swiping left / right on the iPhone?

有没有简单的方法可以检测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");
 }

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

您走在正确的轨道上。 从touchesBe开始,您应该存储用户首次触摸屏幕的位置。

- (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对象。 它会轻而易举地做到这一点,这真是太酷了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM