将点击手势有效添加到 UICollectionViewCell
的 subview 的最佳方法是什么?从 dequeueReusableCellWithReuseIdentifier
返回已经附加了一堆默认手势识别器(例如 UIScrollView
)。我是否需要检查并查看我的一个自定义手势是否已附加( scrollView.gestureRecognizers
),如果没有,则添加它?我需要我的应用程序的滚动尽可能平滑,因此检查的性能和已创建资源的有效重用是关键。这段代码都发生在 cellForItemAtIndexPath
里面.谢谢。
最佳答案
我想出了一种方法,只需要一个共享的点击手势识别器对象,并从 cellForItemAtIndexPath
移动设置代码。 (当用户滚动时它被频繁调用)到 viewDidLoad
(在加载 View 时调用一次)。这是代码:
- (void)myCollectionViewWasTapped:(UITapGestureRecognizer *)tap
{
CGPoint tapLocation = [tap locationInView:self.collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:tapLocation];
if (indexPath)
{
MyCollectionViewCell *cell = (MyCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
CGRect mySubviewRectInCollectionViewCoorSys = [self.collectionView convertRect:cell.mySubview.frame fromView:cell];
if (CGRectContainsPoint(mySubviewRectInCollectionViewCoorSys, tapLocation))
{
// Yay! My subview was tapped!
}
}
}
- (void)viewDidLoad
{
// Invoke super
[super viewDidLoad];
// Add tap handler to collection view
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myCollectionViewWasTapped:)];
[self.collectionView addGestureRecognizer:tap];
}
关于ios - 如何向从 dequeueReusableCellWithReuseIdentifier 返回的 UICollectionViewCell subview 添加点击手势,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876519/