How can i find indexPath
for cell
in the middle of UICollectionView
?
I have horizontal scrolling and only one big cell<
Based on @micantox answer. Updated code for Swift 5
let initialPinchPoint = CGPoint(x: collectionView.center.x + collectionView.contentOffset.x,
y: collectionView.center.y + collectionView.contentOffset.y)
Thank you micantox!
I had multiple visible cells of UICollectionView and needed to position the cell at the centre of the collection view. Something similar to Adobe Content Viewer. If someone is struggling with similar scenario:
#pragma mark - UIScrollViewDelegate methods
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
CGPoint centerPoint = CGPointMake(self.pageContentCollectionView.center.x + self.pageContentCollectionView.contentOffset.x,
self.pageContentCollectionView.center.y + self.pageContentCollectionView.contentOffset.y);
NSIndexPath *centerCellIndexPath = [self.pageContentCollectionView indexPathForItemAtPoint:centerPoint];
[self.pageContentCollectionView scrollToItemAtIndexPath:centerCellIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
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.
I made like for horizontal UICollectionView I use Swift 2.x.
private func findCenterIndex() {
let collectionOrigin = collectionView!.bounds.origin
let collectionWidth = collectionView!.bounds.width
var centerPoint: CGPoint!
var newX: CGFloat!
if collectionOrigin.x > 0 {
newX = collectionOrigin.x + collectionWidth / 2
centerPoint = CGPoint(x: newX, y: collectionOrigin.y)
} else {
newX = collectionWidth / 2
centerPoint = CGPoint(x: newX, y: collectionOrigin.y)
}
let index = collectionView!.indexPathForItemAtPoint(centerPoint)
print(index)
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
findCenterIndex()
}
UICollectionView
has a method - (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point
.
This method return the index path of the item at the specified point. You could calculate the point that represents the center of the UICollectionView
and then use that CGPoint
and this method to retrieve the index path of the item you want to delete.