Thanos
Thanos

Reputation: 854

Trouble reloading UICollectionView's supplementary view (header) with invalidationContext

I have a use case where I have a UICollectionView used to display photos. This collection view has a supplementary view (header) that displays the photo count.

My business logic requires at some point to insertItems(at:) or removeItems(at:) from the collection view so the supplementary view needs to get reloaded in order for the photo count to be updated.

I am looking for a generic solution (a UICollectionView extension would be favourable) to be able to reload/refresh just the collection view's supplementary view.

I do not want solutions that:

I just need something that triggers func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView and redraws the supplementary view.

I have tried this, but it crashes with generic NSException:

 self.photosCollectionView.insertItems(at: [IndexPath(row: index, section:0)])

 let context = UICollectionViewLayoutInvalidationContext()
                context.invalidateSupplementaryElements(ofKind: UICollectionElementKindSectionHeader, at: [IndexPath(row: 0, section: 0)])

 let layout = self.photosCollectionView.collectionViewLayout as? UICollectionViewFlowLayout
                layout?.invalidateLayout(with: context)

Upvotes: 2

Views: 806

Answers (1)

harshal jadhav
harshal jadhav

Reputation: 5684

Inside your insert item method and delete item method, just assign the count to the header view label this way you don't have to reload the collection view

let headerView = collectionViewDemo.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: [0,0]) as? DemoCollectionReusableView
            headerView?.textLabel.text = self.count

Upvotes: 1

Related Questions