Skip to content

Instantly share code, notes, and snippets.

@benjaminsnorris
Created March 10, 2016 03:00
Show Gist options
  • Save benjaminsnorris/a19cb14082b28027d183 to your computer and use it in GitHub Desktop.
Save benjaminsnorris/a19cb14082b28027d183 to your computer and use it in GitHub Desktop.
Snap to center collection view cell
class CollectionViewController: UIViewController {
...
func snapToCenter() {
let centerPoint = view.convertPoint(view.center, toView: collectionView)
guard let centerIndexPath = collectionView.indexPathForItemAtPoint(centerPoint)
collectionView.scrollToItemAtIndexPath(centerIndexPath, atScrollPosition: .CenteredHorizontally, animated: true)
}
...
}
// MARK: - Scroll view delegate
extension CollectionViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
snapToCenter()
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
snapToCenter()
}
}
}
@vipulRajput
Copy link

vipulRajput commented Sep 15, 2020

Hey man, I wanna say that this is the cleanest solution I got for this problem and working so nicely.
have a good day :) 🥇

@aluco100
Copy link

aluco100 commented May 3, 2021

Hey dude, very great job, you simplify a lot of work. Congratulations! 🎉 🥂 🙌

@freakandstein
Copy link

Awesome !!! It's the simplest and great solution I've ever found before to handle snapping scroll view on UIScrollView

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment