Skip to content

Instantly share code, notes, and snippets.

@irace
Created October 24, 2017 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irace/f623a7b61e1c7430cdd6fe44229899ed to your computer and use it in GitHub Desktop.
Save irace/f623a7b61e1c7430cdd6fe44229899ed to your computer and use it in GitHub Desktop.
import UIKit
/**
Enables smooth collection view selection by de-duplicating calls to `selectItemAtIndexPath:animated:scrollPosition:`
If `selectItemAtIndexPath:animated:scrollPosition:` is being driven off of something like `scrollViewDidScroll:`
delegate calls, we’d likely be invoking the former needlessly, with the same index path. This can result in jerky
scrolling.
This class will ensure that we ignore any calls to `selectItemAtIndexPath:animated:scrollPosition:` that are identical
to the preceding call.
*/
final class DeduplicatingCollectionViewSelector {
// MARK: - Public
/// Whether the collection view should actually be scrolled. Ignores calls to `selectItemAtIndexPath:animated:scrollPosition:` when `true`.
var enabled: Bool = true
// MARK: - Mutable state
fileprivate var lastIndexPath: IndexPath?
// MARK: - Input
fileprivate let collectionView: UICollectionView
// MARK: - Initialization
init(collectionView: UICollectionView) {
self.collectionView = collectionView
}
// MARK: - Public
func selectItem(at indexPath: IndexPath, scrollPosition: UICollectionViewScrollPosition, animated: Bool) {
guard enabled else { return }
guard indexPath != lastIndexPath else { return }
lastIndexPath = indexPath
collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment