4

I have a UICollectionView contained in an UIViewController that uses a horizontal UICollectionViewFlowLayout. I'm also using a prototype cell created in my UIStoryboard. I want to create a custom paging, so I'm using - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset.

The problem is that every time I'm trying to get the indexPath corresponding to the targetContentOffset (the point in the scroll view where the scroll will stop), the collection view returns nil even though the point is clearly inside the collection view contentSize.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    NSIndexPath *indexPath = [_collectionView indexPathForItemAtPoint:(*targetContentOffset)];
    // Do something with indexPath    
}

What am I doing wrong?

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
DrMonkey68
  • 127
  • 11
  • Why are you using the ivar? Check whether or not `_collectionView` itself is nil first. – 7usam Mar 24 '13 at 21:07
  • I've tried to use the scrollView variable itself but the result is the same. I'm positive both are not nil when I call the method. – DrMonkey68 Mar 24 '13 at 22:25

1 Answers1

0

The collectionView does not know the indexPath for the targetContentOffset yet.

You have to ask the collectionViewLayout to give you the attribute of the item which will be layout at this position.

Try something like this:

UICollectionViewLayoutAttributes *attribute = [_collectionView.collectionViewLayout layoutAttributesForElementsInRect:(CGRect){(*targetContentOffset).x, 0, 10, self.collectionView.bounds.size.height}][0];