Joh*_*rck 1 objective-c ios uicollectionview
什么是有效地将敲击手势添加到UICollectionViewCell从其返回的子视图的最佳方法是什么dequeueReusableCellWithReuseIdentifier,已经附加了一堆默认手势识别器(例如a UIScrollView).我是否需要检查并查看我的一个自定义手势是否已附加(scrollView.gestureRecognizers),如果没有,则添加它?我需要我的应用程序的滚动尽可能顺利,因此检查的性能和已经创建的资源的有效重用是关键.这段代码都发生在里面cellForItemAtIndexPath.谢谢.
我想出了一种方法,它只需要一个共享的轻击手势识别器对象,并将设置代码从cellForItemAtIndexPath(当用户滚动时非常频繁地调用)移动到viewDidLoad(在加载视图时调用一次).这是代码:
- (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];
}
Run Code Online (Sandbox Code Playgroud)