从Tap Gesture中获取特定的Collection View Cell

时间:2012-12-29 01:59:45

标签: ios uicollectionview uitapgesturerecognizer

我有一个显示图像缩略图的UICollectionView。网格中的每个图像视图都有一个Tap Gesture。我的问题是,我怎样才能抓住被敲击的确切细胞?例如。 “点击索引#43”。

其他评论

  • 点击手势是以编程方式创建的,没有使用故事板。
  • 我在这个项目中启用了ARC和Story Board。

这是我最接近的地方:

UICollectionViewController

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];

    CollectionViewCell *Cell = [collectionView
        dequeueReusableCellWithReuseIdentifier:@"Cell"
                                  forIndexPath:indexPath];
    // Enable tap gesture on each ImageView
    [Cell.ImageView setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture)];
    [tapGesture setNumberOfTouchesRequired:1];
    [tapGesture setNumberOfTapsRequired:1];
    [tapGesture setDelegate:self];
    [Cell.ImageView addGestureRecognizer:tapGesture];

    Cell.ImageView.tag = row; // This tags correctly
}


- (void)tapShowImage // Also, for some reason, 
                     // - (void)handleTapGesture:(UITapGestureRecognizer *)sender
                     // doesn't work. I get an invalid selector error.
{
    NSLog(@"%i", Cell.ImageView.tag);
    // Doesn't work because I can't call Cell.ImageView.tag here.
    // Might be because I"m using SDWebImage to load the image
    // into the ImageView above but not sure.
}

1 个答案:

答案 0 :(得分:4)

您无需为每个单元格添加点击识别器。您可以在collectionView:didSelectItemAtIndexPath:方法中获取tapped单元格的indexPath。