How can i find indexPath
for cell
in the middle of UICollectionView
?
I have horizontal scrolling and only one big cell<
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")
}
Swift:
extension UICollectionView {
var centerPoint : CGPoint {
get {
return CGPoint(x: self.center.x + self.contentOffset.x, y: self.center.y + self.contentOffset.y);
}
}
var centerCellIndexPath: IndexPath? {
if let centerIndexPath: IndexPath = self.indexPathForItemAtPoint(self.centerPoint) {
return centerIndexPath
}
return nil
}
}
Usage :
if let centerCellIndexPath: IndexPath = collectionView.centerCellIndexPath {
print(centerCellIndexPath)
}
Swift 3:
extension UICollectionView {
var centerPoint : CGPoint {
get {
return CGPoint(x: self.center.x + self.contentOffset.x, y: self.center.y + self.contentOffset.y);
}
}
var centerCellIndexPath: IndexPath? {
if let centerIndexPath = self.indexPathForItem(at: self.centerPoint) {
return centerIndexPath
}
return nil
}
}
Swift 4
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let indexPath = collectionView.indexPathForItem(at: collectionView.bounds.center)
}
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);
For some of you that might be experiencing some troubles on getting the center, please look at this potential solution:
func centerCell()->UICollectionViewCell? {
// Asuming your scrolling is horizontal
let viewHorizontalCenter = self.view.bounds.width / 2
let center = CGPoint(x: viewHorizontalCenter, y: self.collectionView.center.y)
let convertedPoint = self.view.convert(center, to: self.unitsCollectionView)
let center = CGPoint(x: self.view.bounds.width / 2, y: self.unitsCollectionView.center.y)
let convertedPoint = self.view.convert(center, to: self.unitsCollectionView)
for cell in unitsCollectionView.visibleCells {
if cell.frame.contains(convertedPoint) {
print("Hello")
return cell
}
}
return nil
}
Try this protocol...
protocol CollectionVisibleMidCell {}
extension CollectionVisibleMidCell where Self: UICollectionView {
func getMidVisibleIndexPath() -> IndexPath? {
var visibleRect = CGRect()
visibleRect.origin = self.contentOffset
visibleRect.size = self.bounds.size
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
guard let indexPath = self.indexPathForItem(at: visiblePoint) else { return nil }
return indexPath
}
}
extension UICollectionView: CollectionVisibleMidCell {}