UICollectionView:如何获得节的标题视图?

有一种通过indexPathUICollectionView cellForItemAtIndexPath:获取单元格的方法。 但是我不能find一种方法来获得像页眉或页脚之类的补充视图之后的任何想法吗?

UPDATE

从iOS 9开始,您可以使用-[UICollectionView supplementaryViewForElementKind:atIndexPath:]通过索引path获取补充视图。

原版的

你最好的办法是把你自己的字典映射索引path作为补充视图。 在您的collectionView:viewForSupplementaryElementOfKind:atIndexPath:方法中,将视图放入字典中,然后再返回。 在您的collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath: ,从字典中删除视图。

我想分享我的解决scheme,由rob mayoff提供的解决scheme,但我不能发表评论,所以我把它放在这里:

对于你们中每一个试图保留收集视图使用的补充视图的参考,但是由于

 collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath: 

被调用的次数太多,请尝试使用NSMapTable而不是字典。

我用

 @property (nonatomic, strong, readonly) NSMapTable *visibleCollectionReusableHeaderViews; 

像这样创build:

 _visibleCollectionReusableHeaderViews = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableWeakMemory]; 

所以当你保留对补充视图的引用时:

 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { // ( ... ) [_visibleCollectionReusableHeaderViews setObject:cell forKey:indexPath]; 

它在NSMapTable中只保留一个WEAK引用,并且保持它很长,因为对象没有被释放。

您不再需要从中删除视图

 collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath: 

因为一旦视图被释放,NSMapTable将丢失条目。

首先你要做的是在集合视图的属性检查器中勾选“Section Header”。 然后添加一个可重用的集合视图,就像您将单元格添加到集合视图一样,编写一个标识符并根据需要为其创build一个类。 然后执行该方法:

 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 

从那里做就像你做cellForItemAtIndexPath它也很重要,以指定是否它的头或脚你编码:

 if([kind isEqualToString:UICollectionElementKindSectionHeader]) { Header *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerTitle" forIndexPath:indexPath]; //modify your header return header; } else { EntrySelectionFooter *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"entryFooter" forIndexPath:indexPath]; //modify your footer return footer; } 

使用indexpath.section知道这是什么部分也注意到,Header和EntrySelectionFooter是我做的UICollectionReusableView的自定义子类