如何刷新UICollectionView补充视图(HeaderView)

问题描述:

首先第一件事情:如何刷新UICollectionView补充视图(HeaderView)

  1. 我不想重装整个的CollectionView。
  2. 我也不想重新加载该部分(因为它与reloadData相同,因为我的cv只有1个部分)。

我把补充视图中的一些控件,因为这个视图作为一个标题视图。在某些情况下,我想根据需要隐藏/显示控件。为了做到这一点,我需要重新加载补充视图,因为它的数据已经更新。

我曾尝试:

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

这当然崩溃。该代码看起来不正确,但我不知道如何正确构造UICollectionViewLayoutInvalidationContext并告诉collectionview重新加载补充视图。

谢谢。

我不知道你是如何为集合视图的单元格分组的。

最简单的解决办法是使用重新加载特定的细胞:

- (void)reloadItemsAtIndexPaths:(NSArray *)indexPaths 
+0

这只会重新加载正常单元格。我想重新加载补充视图。对不起,我编辑了我的问题,以指示补充视图 – GeneCode

+0

在这种情况下,也许你可以遍历你的uicollectionview中的所有子视图,并只在headerView上设置setNeedsDisplay。您可以使用标签属性来标识headerView – diOS

+0

setNeedsdisplay不会重新加载视图。它只是刷新它。 – GeneCode

如果您只需要更新某个特定部分的标题来看,那么你可以做一些与此类似:

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 
} 

代码片段IndexPath(item: 0, section: indexPath.section)看起来有点不可思议,但事实证明supplementaryView只在该部分的第一个项目上返回。