我有一个简单的问题,是否有人能够成功地在 CollectionView 中创建和实现部分标题,类似于 TableView 中的标题?我做了很多研究,发现了一些代码片段,但没有任何人成功实现这一点的真实例子。我有照片的 CollectionView,我想要实现的是根据拍摄的月份将它们分组。我已经设法将它们分成这些部分,但我现在所拥有的只是每个部分开头上方的空白标题。我想要做的是在那些当前空白的标题中显示月份。每个部分的字母在显示联系人的表格视图中显示的方式相同。提前感谢您的回复。
问问题
47559 次
2 回答
35
在 Storyboard 中启用部分页眉/页脚视图。
实现
collectionView:viewForSupplementaryElementOfKind
方法。
看到这个链接
于 2014-05-09T18:37:47.663 回答
19
在集合视图中添加部分标题对我来说适用于以下设置:
添加一个 xib 文件来定义标题视图内容。xib 文件仅包含一种单元类型定义。在我的例子中,标题视图有一个从 UICollectionViewCell 派生的自定义类型 (ImageCollectionViewHeaderCell)。我认为这是必需的,但我不确定。单元标识符也设置为预定义的字符串(例如)“ImageCollectionViewHeaderCellId”
为自定义类型添加头文件和实现文件。有一个方法来获取它的 UINib 对象很方便(一种在步骤 1 中创建的 xib 文件的代理)
@implementation ImageCollectionViewHeaderCell + (UINib*) nib { return [UINib nibWithNibName:@"nameOfXibFileCreatedAtStep1" bundle:nil]; } @end
在集合视图控制器(在我的例子中,它也是 UICollectionView 的 dataSource 和委托)中,在 viewDidLoad 方法中,添加补充元素类型的注册
- (void) viewDidLoad { [_collectionView registerNib:[ImageCollectionViewHeaderCell nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ImageCollectionViewHeaderCellId"]; }
在集合视图控制器中,添加返回非空标题高度和标题视图实例的方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { return CGSizeMake(0., 30.); } - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { NSAssert([kind isEqualToString:UICollectionElementKindSectionHeader], @"Unexpected supplementary element kind"); UICollectionReusableView* cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:ImageCollectionViewHeaderCellIdentifier forIndexPath:indexPath]; NSAssert([cell isKindOfClass:[ImageCollectionViewHeaderCell class]], @"Unexpected class for header cell"); ImageCollectionViewHeaderCell* header_view = (ImageCollectionViewHeaderCell*) cell; // custom content return cell; }
于 2014-04-14T13:57:39.660 回答