【问题标题】:UICollectionView with section headers like a UITableView带有部分标题的 UICollectionView,如 UITableView
【发布时间】:2014-01-21 12:05:43
【问题描述】:
我有一个简短的问题,是否有人能够成功地在 CollectionView 中创建和实现部分标题,类似于 TableView 中的标题?我做了很多研究,发现了sn-ps的代码,但没有任何人成功实现这一点的真实例子。我有照片的 CollectionView,我想要实现的是根据拍摄的月份将它们分组。我已经设法将它们分成这些部分,但我现在所拥有的只是每个部分开头上方的空白标题。我想要做的是在那些当前空白的标题中显示月份。每个部分的字母在显示联系人的表格视图中显示的方式相同。感谢您提前回复。
【问题讨论】:
标签:
ios
objective-c
uitableview
uicollectionview
sectionheader
【解决方案1】:
在 Storyboard 中启用节页眉/页脚视图。
实现collectionView:viewForSupplementaryElementOfKind方法。
见This Link
【解决方案2】:
在集合视图中添加部分标题对我来说适用于以下设置:
添加一个 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;
}