简体   繁体   English

如果将轻按手势识别器添加到其背景视图,则不会调用iOS didSelectItemAtIndexPath

[英]iOS didSelectItemAtIndexPath doesn't get called if a tap gesture recognizer is added to its background view

I have a UIView A, and I added a UICollectionView B to A as a subView, so now view A is B's background view. 我有一个UIView A,并且向A添加了一个UICollectionView B作为子视图,因此现在视图A是B的背景视图。 Here didSelectItemAtIndexPath will get called normally at this time. 这时didSelectItemAtIndexPath此时会正常调用。 But if I add a tap gesture recognizer to View A, then didSelectItemAtIndexPath won't be called. 但是,如果我向视图A添加了轻击手势识别器,则不会调用didSelectItemAtIndexPath The code is simple like below 代码很简单,如下所示

UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap2)];
[viewA addGestureRecognizer:tap2];

How can I make didSelectItemAtIndexPath get called for this situation? 如何针对这种情况调用didSelectItemAtIndexPath My expected behavior is both tapping cell and tapping background methods get called normally and separately as they have different tap behaviors. 我的预期行为是轻击单元格和轻击后台方法都可以正常调用,并且会分别调用,因为它们具有不同的轻击行为。

From Apple's documentation: 从Apple的文档中:

You should always attach your gesture recognizers to the collection view itself—not to a specific cell or view. 您应该始终将手势识别器附加到集合视图本身,而不是附加到特定的单元格或视图。 The UICollectionView class is a descendant of UIScrollView, so attaching your gesture recognizers to the collection view is less likely to interfere with the other gestures that must be tracked. UICollectionView类是UIScrollView的后代,因此将手势识别器附加到集合视图的可能性较小,不会干扰其他必须跟踪的手势。 In addition, because the collection view has access to your data source and your layout object, you still have access to all the information you need to manipulate cells and views appropriately. 另外,由于集合视图可以访问您的数据源和布局对象,因此您仍然可以访问适当地操作单元格和视图所需的所有信息。

https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/IncorporatingGestureSupport/IncorporatingGestureSupport.html https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/CollectionViewPGforIOS/IncorporatingGestureSupport/IncorporatingGestureSupport.html

I have done this and it works very well. 我已经做到了,并且效果很好。 Generally I would call indexPathForItemAtPoint: on the collectionView to get the indexPath and then get the cell from cellForItemAtIndexPath . 通常,我会在collectionView上调用indexPathForItemAtPoint:以获取indexPath,然后从cellForItemAtIndexPath获取单元格。 In your case you can check to see that indexPathForItemAtPoint returns nil (ie the user is clicking on an area between the cells) and then do your code for that. 在您的情况下,您可以检查indexPathForItemAtPoint返回nil(即用户单击单元格之间的区域),然后为此执行代码。 You can also use UIView convertRect methods to figure out exactly where the touch it. 您还可以使用UIView convertRect方法来准确确定触摸的位置。

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

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