ios - 如何向从 dequeueReusableCellWithReuseIdentifier 返回的 UICollectionViewCell subview 添加点击手势

标签 ios objective-c uicollectionview

将点击手势有效添加到 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/

相关文章:

ios - 如何激活和停用定时器?

ios - 重新加载数据后未调用 UICollectionView 数据源方法

ios - UICollectionView 的框架未正确更新为 UITableViewCell subview

ios - 快速后台计时器

ios - 在 UIPickerView 问题中选择第一行

ios - 暂停和恢复加载屏幕的 CABasicAnimation?

iphone - 是否可以在 ScrollView 中制作单选按钮

swift - 在 tableviewcell 上覆盖按钮,里面有 collectionview

iphone - 单击 UISearchBar 的取消按钮后,如何使用 UISearchBar 刷新我的 UITableView?

ios - 使用 backBarButtonItem 禁用动画