Reputation: 8201
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?
Upvotes: 3
Views: 2240
Reputation: 699
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.
Upvotes: 2
Reputation: 7343
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:
Upvotes: 2
Reputation: 5247
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.
Upvotes: 1