滑动ios手势

时间:2014-02-09 19:06:42

标签: ios objective-c uigesturerecognizer uiswipegesturerecognizer

我正在尝试创建一个简单的应用程序,用户可以向左滑动然后向右滑动,同时保持手指在屏幕上。我想计算他们做了多少次滑动,包括改变方向。我正在使用具有方向的uiswipegesture,但它只是在新的滑动时调用动作。为了更有意义,它几乎测试用户可以在特定时间范围内从左到右移动手指的时间。目前我在viewdidload中有这些方法

UISwipeGestureRecognizer *oneFingerSwipeLeft = [[UISwipeGestureRecognizer alloc]
                                                 initWithTarget:self
                                                 action:@selector(oneFingerSwipeLeft:)];
[oneFingerSwipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[[self view] addGestureRecognizer:oneFingerSwipeLeft];

然后将其作为动作

-(void) oneFingerSwipeLeft:(UIGestureRecognizer*)recognizer {
NSLog(@"user swipped left");
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

我会做这样的事情。

设置一些变量来存储您要跟踪的内容:

@property (nonatomic) int swipeCount;
@property (nonatomic) CGPoint previousLocation;

创建UIPanGestureRecognizer:

UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didRecognizePanWithGestureRecognizer:)];
[gesture setDelegate:self];
[self.view addGestureRecognizer:gesture];

处理回调

- (void)didRecognizePanWithGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
    switch (gestureRecognizer.state)
    {
        case UIGestureRecognizerStateBegan:
            [self handleGestureBeganWithRecognizer:gestureRecognizer];
            break;

        case UIGestureRecognizerStateChanged:
            [self handleGestureChangedWithRecognizer:gestureRecognizer];
            break;

        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
            [self handleGestureEndedWithRecognizer:gestureRecognizer];
            break;

        default:
            break;
    }
}

在用户来回滑动时跟踪您要捕获的信息

- (void)handleGestureBeganWithRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
    [self setSwipeCount:0];
    [self setPreviousTouchLocation:[gestureRecognizer locationInView:self.view]];
}

- (void)handleGestureChangedWithRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
    CGPoint currentTouchLocation = [gestureRecognizer locationInView:self.view];
    CGFloat delta = currentTouchLocation.x - self.previousTouchLocation.x;
    [self setPreviousTouchLocation:currentTouchLocation];

    //... figure out if they changed directions based on delta positive or negative

}

- (void)handleGestureEndedWithRecognizer:(UIPanGestureRecognizer *)gestureRecognizer
{
    //.... finish up
}