水平滚动UIScrollView与垂直平移手势

时间:2012-10-02 16:41:41

标签: objective-c ios uiscrollview uipangesturerecognizer

我正在尝试实现一个UIScrollView,其中水平平移滚动浏览滚动视图中的图片,但垂直平移执行我的另一个操作。现在我有一个UIScrollView分页显示垂直滚动禁用,可以很好地滚动浏览图片,但我疯了,试图找到一种方法来拦截垂直平底锅,并调用我自己的方法而不是垂直平底锅只是被吃掉了滚动视图。我能够做到

    UIPanGestureRecognizer *panUp = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
[self.scrollView addGestureRecognizer:panUp];
[scrollView.panGestureRecognizer setEnabled:NO];

这使我可以完全控制我的handlePanGesture:方法中的平移,但这并不是特别有用,因为我觉得我基本上会重写所有我想要避免的滚动逻辑。任何有关如何实现这一目标的帮助或指导将不胜感激。

谢谢!

3 个答案:

答案 0 :(得分:10)

从iOS 5开始,UIScrollView exposes its UIPanGestureRecognizer。将自定义滑动的delegate设置为self,并将gestureRecognizer设置为属性或ivar,并使您的类符合<UIGestureRecognizerDelegate>协议。然后,像这样实施UIGestureRecognizerDelegate的{​​{1}}:

– gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:

答案 1 :(得分:9)

我添加了UIPanGestureRecognizer,然后设置gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:,如下所示:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if ([gestureRecognizer isEqual:self.panGesture] && [otherGestureRecognizer isEqual:self.collectionView.panGestureRecognizer]){
        return YES;
    }
    return NO;
}

我还在gestureRecognizerShouldBegin:

中添加了一张支票
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer isEqual:self.panGesture]) {
        if (gestureRecognizer.numberOfTouches > 0) {
            CGPoint point = [gestureRecognizer locationOfTouch:0 inView:gestureRecognizer.view];
            CGFloat distX = abs(self.collectionView.lastTouchPos.x - point.x);
            CGFloat distY = abs(self.collectionView.lastTouchPos.y - point.y);
            if (distX > distY) {
                return NO;
            }
        } else {
            return NO;
        }
    }
    return YES;
}

仅在向上或向下平移时使用self.panGesture

<强>更新

https://stackoverflow.com/a/8603839/667834似乎有更好的gestureRecognizerShouldBegin

方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer isEqual:self.panGesture]) {
        if (gestureRecognizer.numberOfTouches > 0) {
            CGPoint translation = [self.panGesture velocityInView:self.collectionView];
            return fabs(translation.y) > fabs(translation.x);
        } else {
            return NO;
        }
    }
    return YES;
}

答案 2 :(得分:4)

我认为如果你想使用平移手势会很困难,因为滚动视图会使用这些手势。但是,如果您可以使用滑动,则很容易实现。

    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    swipe.direction = UISwipeGestureRecognizerDirectionDown | UISwipeGestureRecognizerDirectionUp;
    [self.scrollView addGestureRecognizer:swipe];

我对此进行了测试,并且它可以很好地调用处理程序,并且您不需要禁用滚动视图的平移手势识别器(在我的测试中,滚动视图足够高并且内容足够短以至于没有垂直滚动 - 我不知道这是否有必要。)