Home > Back-end >  UICollectionView crashes when scrolling to last item
UICollectionView crashes when scrolling to last item

Time:12-17

There is a ViewController in my app that fetches comments in real time. When a new comment is fetched, I scroll to the bottom of the vertical CollectionView. The thing is that my Crashlytics show many crashes on the scrollToItem call and I can't re-create it myself.

I can't understand how it is possible to crash since I've taken every possible value into account. I ask the CollectionView how many items it has and if it has at least one, scroll to the last one.

Here’s my code:

fileprivate func handleFetchedCommentsResponse() {
    DispatchQueue.main.async {
        self.chatCollectionView.reloadData()
    }
    
    // -------------------------------------------
    
    let numberOfItems = chatCollectionView.numberOfItems(inSection: 0)
    
    if numberOfItems > 0 {
        DispatchQueue.main.async {
            self.chatCollectionView.scrollToItem(at: IndexPath(row: numberOfItems, section: 0), at: .bottom, animated: false)
        }
    }
}

And here's the crash log:

Fatal Exception: NSInternalInconsistencyException Attempted to scroll the collection view to an out-of-bounds item (20) when there are only 20 items in section 0. Collection view: <UICollectionView: 0x10b06f400; frame = (12 480.667; 396 355.333); clipsToBounds = YES; autoresize = RM BM; gestureRecognizers = <NSArray: 0x281d426d0>; layer = <CALayer: 0x280afe280>; contentOffset: {0, 568.33333333333337}; contentSize: {396, 876}; adjustedContentInset: {0, 0, 0, 0}; layout: <UICollectionViewFlowLayout: 0x107b3bab0>; dataSource: <NUP.VoiceRoomViewController: 0x10b019800>>.

PS: My CollectionView has only one section

CodePudding user response:

If your collection view has 20 items, they are going to be at rows 0 through 19. Trying to scroll to a row that matches the count will go past the end of the view's contents.

(If you can't re-create the problem, I'll guess that you're testing with values that don't cause actual scrolling to happen.)

  • Related