Loozie Loozie - 5 months ago 56
iOS Question

getting touch location of uicollectionviewcell

I am trying to get the touch location inside the selected
UICollectionviewCell. I have a UIViewController, vc, containing a UICollectionView, collectionView, as its view. Inside the collectionView are UICollectionViewCells. The vc conforms to the

UICollectionViewDelegate
so preferably I would like to get the touched location inside the delegate callback,
collectionView:(UICollectionView *)collection didSelectItemAtIndexPath:(NSIndexPath *)indexPath
, (if possible). Any recommendation on how to do that? Thanks.

+--------------------------------------------+
| UICollectionView |
| |
| +-------------+ +-------------+ |
| | UICollec | | | |
| | tionView | | | |
| | Cell | | *<---------------<Touch here
| | | | | |
| +-------------+ +-------------+ |
| |
+--------------------------------------------+


*UPDATE*
I ended up detecting the tap on the
UIViewCollectionView
using the
UIGestureRecognizer
and then converting the tap point to the
UICollectionViewCell
view. Please let me know if there's a better way. Thanks.

-(void) viewDidLoad {
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[tapGesture setNumberOfTapsRequired:1];
[self.collectionView addGestureRecognizer:tapGesture];
}

-(void) handleTap:(UIGestureRecognizer*) gesture {
if (gesture.state == UIGestureRecognizerStateEnded) {
CGPoint tappedPoint = [gesture locationInView:_collectionView];
NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:tappedPoint];
CollectionViewCell *cell = (CollectionViewCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
CGPoint pointWRTCell = [cell convertPoint:tappedPoint fromView:self.collectionView];
NSLog(@"collectionView point(%1.1f,%1.1f); cell point (%1.1f,%1.1f)",
tappedPoint.x,tappedPoint.y,pointWRTCell.x,pointWRTCell.y);
}
}

Answer

You will likely need a custom cell to do this. didSelectItemAtIndexPath only tells you a cell was selected. Not where inside the cell it was touched.

Comments