Forked from benjaminsnorris/CollectionViewController.swift
Created
September 15, 2020 10:49
-
-
Save vipulRajput/088ba4bbda74939979b12dc1766079f3 to your computer and use it in GitHub Desktop.
Snap to center collection view cell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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