在使用UICollectionView 时, 设置分区头时,
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;
返回值不能为 nil
我开始写时, 写成下面样子,然后就报错
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if ([kind isEqualToString:UICollectionElementKindSectionHeader])
{
if (indexPath.section == 0)
{
HomeCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:firstReusableView forIndexPath:indexPath];
return view;
}
else
{
HomeCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:secondReusableView forIndexPath:indexPath];
return view;
}
}
return nil;
}
报错信息:*** Assertion failure in -[UICollectionView _createPreparedSupplementaryViewForElementOfKind:atIndexPath:withLayoutAttributes:applyAttributes:], /SourceCache/UIKit/UIKit-2903.2/UICollectionView.m:1401
后来多方查找原因, 发现, 以上方法, 必须返回一个有效的值.
正确的写法:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *view;
if ([kind isEqualToString:UICollectionElementKindSectionHeader])
{
if (indexPath.section == 0)
{
view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:firstReusableView forIndexPath:indexPath];
}
else
{
view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:secondReusableView forIndexPath:indexPath];
}
}
return view;
}