与 this question 有类似的问题,我正在尝试将双击手势识别器添加到我的 UICollectionView
实例。
我需要防止默认单击调用 UICollectionViewDelegate
方法collectionView:didSelectItemAtIndexPath:
.
为了实现这一点,我实现了代码 straight from Apple's Collection View Programming Guide (Listing 4-2) :
UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)]; NSArray* recognizers = [self.collectionView gestureRecognizers]; // Make the default gesture recognizer wait until the custom one fails. for (UIGestureRecognizer* aRecognizer in recognizers) { if ([aRecognizer isKindOfClass:[UITapGestureRecognizer class]]) [aRecognizer requireGestureRecognizerToFail:tapGesture]; } // Now add the gesture recognizer to the collection view. tapGesture.numberOfTapsRequired = 2; [self.collectionView addGestureRecognizer:tapGesture];
此代码未按预期工作:
tapGesture
在双击时触发,但不会阻止默认单击,并且委托(delegate)的 didSelect...
方法仍然被调用。在调试器中单步执行会发现 if 条件
[aRecognizer isKindOfClass:[UITapGestureRecognizer class]]
, 永远不会评估为真,因此新的 tapGesture
上的失败要求没有建立。每次通过 for 循环运行此调试器命令:
po (void)NSLog(@"%@",(NSString *)NSStringFromClass([aRecognizer class]))
表明默认手势识别器(确实)不是
UITapGestureRecognizer
实例。相反,它们是私有(private)类(class)
UIScrollViewDelayedTouchesBeganGestureRecognizer
和 UIScrollViewPanGestureRecognizer
.首先,我不能在不违反私有(private) API 规则的情况下明确使用这些。二、附上
UIScrollViewDelayedTouchesBeganGestureRecognizer
通过 requireGestureRecognizerToFail:
无论如何似乎都没有提供所需的行为 - 即委托(delegate)的 didSelect...
仍然被称为。我如何使用
UICollectionView
的默认手势识别器将双击添加到 Collection View 并防止默认单击也触发委托(delegate)的 collectionView:didSelectItemAtIndexPath:
方法?提前致谢!
最佳答案
我的解决方案是不实现 collectionView:didSelectItemAtIndexPath 而是实现两个手势识别器。
self.doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processDoubleTap:)];
[_doubleTapGesture setNumberOfTapsRequired:2];
[_doubleTapGesture setNumberOfTouchesRequired:1];
[self.view addGestureRecognizer:_doubleTapGesture];
self.singleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processSingleTap:)];
[_singleTapGesture setNumberOfTapsRequired:1];
[_singleTapGesture setNumberOfTouchesRequired:1];
[_singleTapGesture requireGestureRecognizerToFail:_doubleTapGesture];
[self.view addGestureRecognizer:_singleTapGesture];
这样我就可以处理单击和双击。我能看到的唯一问题是在 doubleTaps 上选择了单元格,但如果这让您感到困扰,您可以在两个选择器中处理它。
关于uigesturerecognizer - 双击 UICollectionView;需要单击才能失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17671498/