问题描述
我想对UICollectionView中的单元格进行双击,并选择双击动作取消单元格。
I want to respond to double-taps on cells in a UICollectionView, and have a double-tap action cancel cell selection.
这就是我试过的:
UITapGestureRecognizer *tapRecogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
tapRecogniser.numberOfTapsRequired = 2;
for (UITapGestureRecognizer *recogniser in [self.collectionView gestureRecognizers]) {
[recogniser requireGestureRecognizerToFail:tapRecogniser];
}
[self.collectionView addGestureRecognizer:tapRecogniser];
也就是说,如果我的双击手势识别器,我试图让默认手势识别器失败成功。
That is, I am trying to get the default gesture recognisers to fail if my double-tap gesture recogniser succeeds.
这似乎不起作用,因为我的集合视图委托的 collectionView:didSelectItemAtIndexPath:
仍在获得双击后调用
This doesn't appear to work, as my collection view delegate's collectionView:didSelectItemAtIndexPath:
is still getting called after a double-tap
在这一点上具有误导性,声称默认手势识别器是UITapGestureRecognizer子类的一个实例,因此可以使用 [recogniser isKindOfClass:[UITapGestureRecognizer class]]轻松选择它。
。不幸的是这是一个错误。
Apple's documentation is misleading on this point, claiming that the default gesture recogniser is an instance of a UITapGestureRecognizer subclass, so it can be easily picked out with [recogniser isKindOfClass:[UITapGestureRecognizer class]]
. Unfortunately this is an error.
推荐答案
我不明白你为什么需要requireToFail。我在UICollectionView中使用双击并且它不会干扰我的单击(用于选择)。
I don't see why you need the requireToFail. I use double-taps in a UICollectionView and it doesn't interfere with my single taps (used for selection).
我使用以下内容:
UITapGestureRecognizer *doubleTapFolderGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(processDoubleTap:)];
[doubleTapFolderGesture setNumberOfTapsRequired:2];
[doubleTapFolderGesture setNumberOfTouchesRequired:1];
[self.view addGestureRecognizer:doubleTapFolderGesture];
然后,这个:
- (void) processDoubleTap:(UITapGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateEnded)
{
CGPoint point = [sender locationInView:collectionView];
NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:point];
if (indexPath)
{
NSLog(@"Image was double tapped");
}
else
{
DoSomeOtherStuffHereThatIsntRelated;
}
}
}
似乎工作正常 - 双击被识别,我可以按照自己的意愿处理它(在这种情况下,我正在扩展文件夹的内容)。但单击会导致选择抽头销售,我没有写任何手势识别。
Seems to working fine -- the double tap is recognized and I can handle it as I wish (in this case I'm expanding the contents of a folder). But a single-tap will cause the tapped sell to be selected, which I haven't written any gesture recognition for.
重要编辑:
我正在重新审视这个问题,因为我已经看到我的原始答案在某些情况下可能是错误的,并且有一个明显的解决方案似乎有效。
需要添加以下行:
doubleTapFolderGesture.delaysTouchesBegan = YES;
消除了单击选择电池的干扰。这提供了更强大的设置。
which eliminates interference with the single tap for cell selection. This provides a much more robust setup.
这篇关于如何在UICollectionView中检测单元格上的双击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!