StickyGridCollectionView-Final
StickyGridCollectionView-Final copied to clipboard
Crash on reloadData()
Hey, Whenever I try to call collectionView.reloadData() , the layout crashes with error "index 0 beyond bounds for empty array"
I am getting the same error. were you able to fix it @rishabhntl17
@aatish-rajkarnikar @rishabhntl17 did someone found a solution?
@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!
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
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.