Donny
Donny

Reputation: 94

How to get the location of the UICollectionViewCell in self.view?

I used the code below to get the location of the cell when touched. However, when the UICollectionView.bounds.size.width > 320, or > 640, the "origin.x" returned often > 320, for example, 657, 469. Cause there are some images inside cells. So when I touched the cell on the second page. The value X returned may be 368.0 or other values.

I just need to get the value X in the current view.(320 * 480).

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath]; - (void)viewDidLoad { // attach long press gesture to collectionView UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; lpgr.minimumPressDuration = .5; //seconds lpgr.delegate = self; [self.collectionView addGestureRecognizer:lpgr]; } -(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state != UIGestureRecognizerStateEnded) { return; } CGPoint p = [gestureRecognizer locationInView:self.collectionView]; NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:p]; if (indexPath == nil){ NSLog(@"couldn't find index path"); } else { // get the cell at indexPath (the one you long pressed) UICollectionViewCell* cell = [self.collectionView cellForItemAtIndexPath:indexPath]; // do stuff with the cell } }

Upvotes: 0

Views: 359

Answers (1)

Stonz2
Stonz2

Reputation: 6396

If I understand your question correctly, your collection view may have multiple pages horizontally. Assuming these pages are frame-width, you could do this:

int xVal = (int)p.x % (int)self.view.frame.size.width;

Keep in mind that you will lose decimal precision.

Upvotes: 1

Related Questions