I have UICollectionView
with horizontal scrolling and there are always 2 cells side-by-side per the entire screen. I need the scrolling to stop at the begining
Here is my version of it in Swift 3. Calculate the offset after scrolling ended and adjust the offset with animation.
collectionLayout
is a UICollectionViewFlowLayout()
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let index = scrollView.contentOffset.x / collectionLayout.itemSize.width
let fracPart = index.truncatingRemainder(dividingBy: 1)
let item= Int(fracPart >= 0.5 ? ceil(index) : floor(index))
let indexPath = IndexPath(item: item, section: 0)
collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}