yhl
yhl

Reputation: 689

Grab specific Collection View Cell from Tap Gesture

I have a UICollectionView displaying image thumbnails. Each Image View in the grid has a Tap Gesture. My question is, how can I grab the exact cell that was tapped? E.g. "Tapped on index # 43".

Additional Comments

Here's the closest I've come:

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.
}

Upvotes: 1

Views: 2158

Answers (1)

rdelmar
rdelmar

Reputation: 104082

You don't need to add a tap recognizer to each of your cells. You can get the indexPath of the tapped cell in the collectionView:didSelectItemAtIndexPath: method.

Upvotes: 4

Related Questions