Created
October 24, 2017 18:42
-
-
Save irace/f623a7b61e1c7430cdd6fe44229899ed to your computer and use it in GitHub Desktop.
This file contains 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
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