how to get indexPath for cell which is located in the center of UICollectionView how to get indexPath for cell which is located in the center of UICollectionView ios ios

how to get indexPath for cell which is located in the center of UICollectionView


Like you did yourself, indexPathForItemAtPoint is a good way of finding the index path of the element you're interested in. If your question is: how do i know the coordinates of this point? Then you should try with (using the same name you gave it in your code snippet):

initialPinchPoint = CGPointMake(self.collectionView.center.x + self.collectionView.contentOffset.x,                                 self.collectionView.center.y + self.collectionView.contentOffset.y);


This would be better code because it's cleaner and easier to read, all the content offset calculation is superfluous:

     NSIndexPath *centerCellIndexPath = [self.collectionView indexPathForItemAtPoint:[self.view convertPoint:[self.view center] toView:self.collectionView]];

This would also be the correct representation of what you're actually trying to do:
1. Taking the center point of your viewcontroller's view - aka visual center point
2. convert it to the coordinate space of the view you're interested in - which is the collection view
3. Get the indexpath that exist at the location given.


Here's what I did in Swift 3

private func findCenterIndex() {    let center = self.view.convert(self.collectionView.center, to: self.collectionView)    let index = collectionView!.indexPathForItem(at: center)    print(index ?? "index not found")}