Reload UICollectionView header or footer?

2020-02-02 10:44发布

I have some data that is fetched in another thread that updates a UICollectionView's header. However, I've not found an efficient way of reloading a supplementary view such as a header or footer.

I can call collectionView reloadSections:, but this reloads the entire section which is unnecessary. collectionView reloadItemsAtIndexPaths: only seems to target cells (not supplementary views). And calling setNeedsDisplay on the header itself doesn't appear to work either. Am I missing something?

10条回答
叛逆
2楼-- · 2020-02-02 11:10
[UIView performWithoutAnimation:^{
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:4]];
}];

[UIView performWithoutAnimation:^{
    [self.collectionView reloadData];
}];
查看更多
干净又极端
3楼-- · 2020-02-02 11:10
let headerView = collectionView.visibleSupplementaryViews(ofKind: UICollectionView.elementKindSectionHeader)[0] as! UICollectionReusableView

I've used above method to get current header, and successfully updated subviews on it.

查看更多
老娘就宠你
4楼-- · 2020-02-02 11:12

Swift 3/4/5 version:

collectionView.collectionViewLayout.invalidateLayout()

Caution!

If you change the number of collectionView items at the same time (for example you show the footer only if all cells were loaded), it will crash. You need to reload the data first, to make sure that the number of items is the same before and after invalidateLayout():

collectionView.reloadData()
collectionView.collectionViewLayout.invalidateLayout()
查看更多
Anthone
5楼-- · 2020-02-02 11:13

I got the same problem. I tried @BobVorks's answer and it is working fine, if only the cell was reused else it won't. So, I tried finding a more cleaner way to achieve this and I came up reloading the whole UICollectionView after the performBatchUpdate (completion block) and it is working great. It reloads the Collection Without any cancellation of animation in the insertItemsAtIndexPath. Actually I personally up voted recent 2 answers cause i find it working but in my case, this is the cleanest way to do it.

[self.collectionView performBatchUpdates:^{
     // perform indexpaths insertion
} completion:^(BOOL finished) {
     [self.collectionView reloadData];
}];
查看更多
登录 后发表回答