Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Reload UICollectionView Supplementary View (HeaderView)

Tags:

First things first:

  1. I do NOT Want to reload whole CollectionView.
  2. I also do NOT want to reload the section either (since it is same as reloadData because my cv only has 1 section).

I put some controls in the Supplementary View since this view acts as a header view. On some case, I want to hide/show the controls as needed. In order to do that I need to reload the Supplementary View as the data for it is already updated.

What I have tried:

UICollectionViewLayoutInvalidationContext *layoutContext =
[[UICollectionViewLayoutInvalidationContext alloc] init];
[layoutContext invalidateSupplementaryElementsOfKind:UICollectionElementKindSectionHeader
                                        atIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
[[_collectionView collectionViewLayout] invalidateLayoutWithContext:layoutContext];

This crash of course. The code doesn't look right either but I am not sure how to construct the UICollectionViewLayoutInvalidationContext properly and telling the collectionview to reload just the Supplementary View.

Thanks.

like image 513
GeneCode Avatar asked Feb 08 '17 08:02

GeneCode


1 Answers

If you need only to update the header view of a particular section, then you can do something similar to this:

if let header = collectionView.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: indexPath.section)) as? MyCollectionHeaderView {
    // Do your stuff here
    header.myLabel.isHidden = true // or whatever
}

Code fragment IndexPath(item: 0, section: indexPath.section) may seem a bit weird, but it turns out that the supplementaryView is only returned on the first item in the section.

like image 122
Ely Avatar answered Sep 24 '22 10:09

Ely