【发布时间】:2012-11-15 09:06:29
【问题描述】:
有一种方法可以通过indexPath (UICollectionView cellForItemAtIndexPath:) 获取单元格。但我找不到一种方法来获取一个补充视图,如页眉或页脚,在创建后。有什么想法吗?
【问题讨论】:
标签: iphone ios uicollectionview
有一种方法可以通过indexPath (UICollectionView cellForItemAtIndexPath:) 获取单元格。但我找不到一种方法来获取一个补充视图,如页眉或页脚,在创建后。有什么想法吗?
【问题讨论】:
标签: iphone ios uicollectionview
从 iOS 9 开始,您可以使用-[UICollectionView supplementaryViewForElementKind:atIndexPath:] 通过索引路径获取补充视图。
最好的办法是制作自己的字典,将索引路径映射到补充视图。在您的 collectionView:viewForSupplementaryElementOfKind:atIndexPath: 方法中,将视图放入字典中,然后再返回。在您的 collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath: 中,从字典中删除视图。
【讨论】:
func supplementaryViewForElementKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView :)
我想分享我对 rob mayoff 提供的解决方案的见解,但我无法发表评论,所以我把它放在这里:
对于每一位试图保持对集合视图正在使用的补充视图的引用,但由于
而遇到过早丢失跟踪问题的每一个人collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:
被调用太多次,尝试使用 NSMapTable 而不是字典。
我用
@property (nonatomic, strong, readonly) NSMapTable *visibleCollectionReusableHeaderViews;
这样创建:
_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 就会丢失条目。
【讨论】:
-applyLayoutAttributes 并获取了索引路径的副本,然后遍历哈希表中的视图并与索引路径进行比较。
您要做的第一件事是在集合视图的属性检查器中选中“Section Header”框。然后添加一个集合可重用视图,就像您将单元格添加到集合视图一样,编写一个标识符并在需要时为其创建一个类。然后实现方法:
- (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 的自定义子类
【讨论】:
kind 是一个NSString。应该使用if ([kind isEqualToString:UICollectionElementKindSectionHeader]) 进行比较,而不是==。
这种方法通常足以达到重新加载屏幕补充视图的目的:
collectionView.visibleSupplementaryViews(ofKind: UICollectionElementKindSectionHeader)
【讨论】: