Skip to content

Instantly share code, notes, and snippets.

@freak4pc
Last active December 5, 2022 11:59
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save freak4pc/0f244f41a5379f001571809197e72b90 to your computer and use it in GitHub Desktop.
Save freak4pc/0f244f41a5379f001571809197e72b90 to your computer and use it in GitHub Desktop.
UICollectionView Extension to scroll to confirm validity of IndexPath before scrolling to it
extension UICollectionView {
func isIndexPathAvailable(_ indexPath: IndexPath) -> Bool {
guard dataSource != nil,
indexPath.section < numberOfSections,
indexPath.item < numberOfItems(inSection: indexPath.section) else {
return false
}
return true
}
func scrollToItemIfAvailable(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) {
guard isIndexPathAvailable(indexPath) else { return }
scrollToItem(at: indexPath, at: scrollPosition, animated: animated)
}
func scrollToItemOrThrow(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) throws {
guard isIndexPathAvailable(indexPath) else {
throw Error.invalidIndexPath(indexPath: indexPath, lastIndexPath: lastIndexPath)
}
scrollToItem(at: indexPath, at: scrollPosition, animated: animated)
}
var lastIndexPath: IndexPath {
let lastSection = numberOfSections - 1
return IndexPath(item: numberOfItems(inSection: lastSection) - 1,
section: lastSection)
}
}
extension UICollectionView {
enum Error: Swift.Error, CustomStringConvertible {
case invalidIndexPath(indexPath: IndexPath, lastIndexPath: IndexPath)
var description: String {
switch self {
case let .invalidIndexPath(indexPath, lastIndexPath):
return "IndexPath \(indexPath) is not available. The last available IndexPath is \(lastIndexPath)"
}
}
}
}
@christoforosl
Copy link

Maybe it needs "import UIKit" ?

@yanfeng42
Copy link

NICE~

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