Home > Blockchain >  Empty collection view crashes when refreshing due to scrolling
Empty collection view crashes when refreshing due to scrolling

Time:10-28

My horizontal collection view (only when it has 0 cells) causes a crash when attempting to refresh the parent view. When there are 0 items (i.e. "shownStations") for the collection view, the collection view is hidden. When refreshing the parent view, an API call is made to get any available items for the collection view. The code of the collection view that seems relevant to the error message (below) is as follows:

        if self.shownStations.isEmpty {  
            self.stationCollectionView?.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
        } else {
            self.stationCollectionView?.frame = CGRect(x: 0, y: 0, width: 414, height: 150)
        }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if !self.hiddenStations.isEmpty {
            return shownStations.count   1
        } else {
            return shownStations.count
        }
    }

Error message: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempted to scroll the collection view to an out-of-bounds item (0) when there are only 0 items in section 0. Collection view: <UICollectionView: 0x7fc5b101f800; frame = (0 0; 0 0); clipsToBounds = YES; autoresize = RM BM; gestureRecognizers = <NSArray: 0x6000022b9fb0>; layer = <CALayer: 0x600002cd1540>; contentOffset: {0, 0}; contentSize: {0, 0}; adjustedContentInset: {0, 0, 0, 0}; layout: <UICollectionViewFlowLayout: 0x7fc5b0912ae0>; dataSource: <Decibel_iOS.HomeFeedViewController: 0x7fc5b1054200>>.'

CodePudding user response:

Somewhere in your program someone is probably calling scrollToItems(at:,scrollPosition:). They either don't know the collection is empty and are just passing in (row:0, item:0) as the index path instead of just skipping the scroll call altogether. Or they think your collection contains at least one item.

To further diagnose the issue, I would either set a breakpoint on exceptions or set a breakpoint on the UIScrollView function and look at the backtrace to see who is making the call.

You also want to check your Data Source to make sure it's been updated with the correct number of items at the time the scroll happens.

But having a backtrace to find out who or what is causing the scrollview to scroll would be a great first step.

  • Related