StickyGridCollectionView-Final icon indicating copy to clipboard operation
StickyGridCollectionView-Final copied to clipboard

Crash on reloadData()

Open rishh-hub opened this issue 4 years ago • 5 comments

Hey, Whenever I try to call collectionView.reloadData() , the layout crashes with error "index 0 beyond bounds for empty array"

rishh-hub avatar Jun 08 '20 12:06 rishh-hub

I am getting the same error. were you able to fix it @rishabhntl17

aatish-rajkarnikar avatar Jul 12 '20 10:07 aatish-rajkarnikar

@aatish-rajkarnikar @rishabhntl17 did someone found a solution?

arthur-stpnv avatar Aug 27 '21 13:08 arthur-stpnv

@aatish-rajkarnikar @arthur-stpnv Hey, in my case I had added a check for nil as it fitted my case if collectionView != nil { collectionView.reloadData() } Let me know if something else works out for you!

rishh-hub avatar Aug 27 '21 14:08 rishh-hub

Apparently, the collectionView is giving a crash if it is not in the current view controller, so try not reloading a collectionView that is beyond the range of screen

rishh-hub avatar Aug 27 '21 15:08 rishh-hub

I solved my issue following way: Instead of using collectionView.reloadData(), I reloaded the sections of the collectionView. In the view controller with my collectionView I implemented the following method:

private func reloadData() {
        guard let collectionView = collectionView else { return }
        var indexSet = IndexSet()
        let rowCount = collectionView.numberOfSections
        
        for row in 0..<rowCount {
             indexSet = [row]
            DispatchQueue.main.async {
                 collectionView.reloadSections(indexSet)
            }
          }
    }

And when I used this method, the sticky rows and columns didn't work properly i.e. the zIndexes of the sticky rows and columns messed up. To fix that, in the custom UICollectionViewFlowLayout class, I implemented the following method:

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attributes = super.layoutAttributesForItem(at: indexPath)
        
        attributes?.zIndex = zIndex(forRow: indexPath.row, column: indexPath.section)
        
        return attributes
    }

It helped to keep layout of the zIndexes proper.

mukatayev1 avatar Nov 26 '21 05:11 mukatayev1