-
-
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
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
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)" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NICE~