Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
like image 406
MobileDev Avatar asked Apr 07 '14 23:04

MobileDev


2 Answers

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.

like image 107
CrimsonChris Avatar answered Nov 06 '22 12:11

CrimsonChris


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.

like image 1
Jaybo Avatar answered Nov 06 '22 10:11

Jaybo