What is the correct syntax for using UICollectionView's indexPathForItemAtPoint?
I'm using the following code to try to identify the cell that is at the centre of the UICollectionView as I scroll through it.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//locate the scrollview which is in the centre
CGPoint centerPoint = CGPointMake(self.collectionView.frame.size.width / 2, self.collectionView.frame.size.height /2);
NSIndexPath *indexPathOfCentralCell = [self.collectionView indexPathForItemAtPoint:centerPoint];
}
However, this always gives me the same indexPath back, no matter how I scroll.
What am I doing wrong?
You are looking up a static point in a static field of cells. Yes you will always get the same cell.
In order to deal with scrolling you need to add the scrollview's position into your check. Something like this:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//locate the scrollview which is in the centre
CGPoint centerPoint = CGPointMake(self.collectionView.frame.size.width / 2 + scrollView.contentOffset.x, self.collectionView.frame.size.height /2 + scrollView.contentOffset.y);
NSIndexPath *indexPathOfCentralCell = [self.collectionView indexPathForItemAtPoint:centerPoint];
}
An example of where you'd want to do this is when you want to capture a gesture on the UICollectionView, and then do something with the specific item in the UICollectionView that falls under the location of the swipe gesture. The code below as a method in your UICollectionViewController will return the correct cell, and accounts for scrolling within the Collection View.
- (UICollectionViewCell *) cellForGesture:(id)sender
{
UISwipeGestureRecognizer * gesture = sender;
CGPoint point = [gesture locationInView:self.view];
NSLog(@"Swipe location: %f, %f", point.x, point.y, nil);
CGPoint pointInCollection = CGPointMake(point.x + self.collectionView.contentOffset.x, point.y + self.collectionView.contentOffset.y);
NSIndexPath * indexPath = [self.collectionView indexPathForItemAtPoint:pointInCollection];
UICollectionViewCell * cell = [self.collectionView cellForItemAtIndexPath:indexPath];
return cell;
}
You might call the above method in a context like this (where revealSupplementalControls
is a custom method on your UICollectionViewCell class):
- (IBAction) swipeLeft:(id)sender {
UICollectionViewCell * cell = [self cellForGesture:sender];
[cell revealSupplementalControls];
}
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