I am trying to make my cells snap into place when scrolling through my collection view. It seems to work fine on iPhone 12 but on iPhone 11 and larger screens it does not let me return to the first cell again and keeps snapping the second cell into the centre.
extension UICollectionView {
func scrollToNearestVisibleCollectionViewCell() {
decelerationRate = UIScrollView.DecelerationRate.normal
let visibleCenterPositionOfScrollView = Float(self.contentOffset.x + (self.bounds.size.width / 2))
var closestCellIndex = -1
var closestDistance: Float = .greatestFiniteMagnitude
for i in 0..<visibleCells.count {
let cell = visibleCells[i]
let cellWidth = cell.bounds.size.width
let cellCenter = Float(cell.frame.origin.x + cellWidth / 2)
let distance: Float = fabsf(visibleCenterPositionOfScrollView - cellCenter)
if distance < closestDistance {
closestDistance = distance
closestCellIndex = self.indexPath(for: cell)!.row
}
}
if closestCellIndex != -1 {
scrollToItem(at: IndexPath(row: closestCellIndex, section: 0), at: .centeredHorizontally, animated: true)
}
}
}
Then applying this to the collection view
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.collectionView.scrollToNearestVisibleCollectionViewCell()
setPageByScrollOffset(scrollView: scrollView)
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
collectionView.scrollToNearestVisibleCollectionViewCell()
}
}