Search code examples
swiftscrolluicollectionviewcrash

collectionView "scrollToItem" after check for "dataSource?.collectionView(self, cellForItemAt:" functions on iOS 18 leads to a crash


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.


Solution

  • 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)
        }
     }
    

    }