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);
}
}
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.
UIView has a method func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView?
. To get the touch point, you can override this method in your collection view or collection view cell.
And there are methods like func convertPoint(_ point: CGPoint, toView view: UIView?) -> CGPoint
for you to convert point in different coordinate systems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With