3
votes

I have an UICollectionView with custom cells. When I tap a cell I get a collectionView: didSelectItemAtIndexPath:.

This doesn't allow me to determine which element inside the cell was tapped (image or label). How to determine which element within the cell was tapped?

3

3 Answers

2
votes

You have to subclass UICollectionViewCell and have these kind of objects in your UICollectioView. Then you create a delegate in the cells with methods like

- (void)collectionCell:(UICollectionViewCell *)cell didTapButtonWithIndex:(NSUInteger)index

and set your view controller as delegate for each of this cell. So you would get the action in these methods instead of collectionView: didSelectItemAtIndexPath:

2
votes

You can set a tap UITapGestureRecognizer to the entire cell and use - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; to get the tapped object

In -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath do this

 UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellTapped:)];
    tapGesture.numberOfTapsRequired = 1;
    [cell addGestureRecognizer:tapGesture];

And in cellTapped

-(void)cellTapped:(UIGestureRecognizer *)gesture
{
    CGPoint tapPoint = [gesture locationInView:gesture.view];
    UIView *tappedView = [gesture.view hitTest:tapPoint withEvent:nil];

    if ([tappedView isKindOfClass:[UILabel class]]) {
        NSLog(@"Found");
    }
}

Please do check to see whether the user interaction is set on the cell and individual subviews like labels and imageview's . Hope this helps.

1
votes

Just add UITapGestureRecognizer to the cell element when creating the cell in cellForItem and add target and selector to call. The selector method will then get a recognizer which has a UIView property, and this property will be your selected element.