I have this extension to scroll to the first collectionView cell:
extension UICollectionView {
func scrollToFirst(inSection: Int = 0, animated: Bool = false) {
if let _ = dataSource?.collectionView(self, cellForItemAt: IndexPath(row: 0, section: inSection)) { // MARK: Checks if collectionView is filled
scrollToItem(at: IndexPath(row: 0, section: inSection), at: .right, animated: animated)
}
}
}
It works on iOS -18 but on iOS 18.0 it crashes.
func scrollToFirst(inSection: Int = 0, animated: Bool = false) {
if visibleCells.count > 0 { // MARK: Checks if collectionView is filled
scrollToItem(at: IndexPath(row: 0, section: inSection), at: .right, animated: animated)
}
}
}
Your dataSource
somehow has not loaded yet. Although the cell’s instance is available, I believe the section
isn’t ready to use, you may want to print out the section by numberOfSections
. It can lead to the exception below:
Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Attempted to scroll the collection view to an out-of-bounds item
So, it’s better to check if the index is valid before scrolling:
if self.numberOfSections > inSection {
//TODO: - other stuff
}