Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vipulRajput/088ba4bbda74939979b12dc1766079f3 to your computer and use it in GitHub Desktop.
Save vipulRajput/088ba4bbda74939979b12dc1766079f3 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()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment