在使用UICollectionView的时候, 设置collectionView的header或者footer后, 报了以下错误:
*** Assertion failure in -[UICollectionView _createPreparedSupplementaryViewForElementOfKind:atIndexPath:withLayoutAttributes:applyAttributes:], /SourceCache/UIKit/UIKit-2935.138/UICollectionView.m:1324
话不多说, 上代码:
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
flowLayout.itemSize = CGSizeMake((310 - 50)/3, 27);
flowLayout.minimumLineSpacing = 10;
flowLayout.minimumInteritemSpacing = 5;
flowLayout.sectionInset = UIEdgeInsetsMake(0, 15, 20, 15);
flowLayout.headerReferenceSize = CGSizeMake(310, 30);
self.filterCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kSCREEN_Width - 310, 64, 310, kSCREEN_Height - 64 - 48) collectionViewLayout:flowLayout];
_filterCollectionView.showsVerticalScrollIndicator = NO;
_filterCollectionView.showsHorizontalScrollIndicator = NO;
_filterCollectionView.delegate = self;
_filterCollectionView.dataSource = self;
_filterCollectionView.backgroundColor = [UIColor whiteColor];
[self addSubview:_filterCollectionView];
[_filterCollectionView registerClass:[LZSkillTipCell class] forCellWithReuseIdentifier:@"SkillTipCell"];
[_filterCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"filterHeader"];
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView *reusableHeaderView = [[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 310, 30)];
[reusableHeaderView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj removeFromSuperview];
}];
UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 0, 50, 30)];
titleLabel.font = [UIFont systemFontOfSize:13];
[reusableHeaderView addSubview:titleLabel];
[titleLabel addLineForSelfWithFrame:CGRectMake(0, 0, 310, 0.5)];
if (indexPath.row == 0) {
titleLabel.text = @"分类";
}else if (indexPath.row == 1){
titleLabel.text = @"所属标签";
}
return reusableHeaderView;
}
return nil;
}
经过debug后发现, 当UICollectionReusableView创建之后, 就会崩溃, 所以分析是这里的问题.
在collectionview的header设置的代理方法中, header或者footer创建需要使用复用机制, 不可以手动创建, 改为以下就可以解决.
UICollectionReusableView *reusableHeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"filterHeader" forIndexPath:indexPath]
产生这个错误往往有这么几种情况:
1.header或者footer的设置没有使用UICollectionReusableView的复用机制, 而是自己手动创建的.
2.UICollectionReusableView复用的情况下, 没有注册header或者footer.
注册代码:
[_filterCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"filterHeader"];