UICollectionView 是没有类似于UITableview的整体表头的,在注册cell时,如果分区表头,表尾也需要注册,如果有个需求:只是简单给UICollectionview加一个类似于tableview的整体表头,可以利用上边距:
self.collectionView.contentInset = UIEdgeInsetsMake(100, 0,0, 0);
UIView *view =[[UIView alloc]initWithFrame:CGRectMake(0, -100, KScreenW, 100)];
view.backgroundColor =[UIColor purpleColor];
[self.collectionView addSubview:view];
[self.collectionView registerNib:[UINib nibWithNibName:@"LXCollectionCell" bundle:nil] forCellWithReuseIdentifier:ID];
[self.collectionView registerNib:[UINib nibWithNibName:@"LXCollectionHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:header];
[self.collectionView registerNib:[UINib nibWithNibName:@"LXCollectionFooterView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footer];
分区表头表尾有时候设置了代理代理方法不走,是因为分区表头表尾的size没有设置,有两种方法,
一:设置 flowLayout.headerReferenceSize = CGSizeMake(KScreenW, 100);
flowLayout.headerReferenceSize = CGSizeMake(KScreenW, 100);
二:设置代理方法里 可针对单独分区进行设置;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableview = nil;
if (kind == UICollectionElementKindSectionHeader){
LXCollectionHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:header forIndexPath:indexPath];
NSString *title = [[NSString alloc] initWithFormat:@"Recipe Group #%ld",indexPath.section +1];
headerView.tagsLabel.text= title;
UIImage *headerImage = [UIImage imageNamed:@"meinv06.jpg"];
headerView.backGroundImage.image = headerImage;
reusableview = headerView;
}
if (kind == UICollectionElementKindSectionFooter){
LXCollectionFooterView *footerView =[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footer forIndexPath:indexPath];
reusableview = footerView;
}
return reusableview;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
return CGSizeMake(KScreenW, 100);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
return CGSizeMake(KScreenW, 100);
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
LXCollectionCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
if (!cell) {
cell =[[LXCollectionCell alloc]init];
}
NSString *image = [recipeImages[indexPath.section]objectAtIndex:indexPath.item];
cell.icon.image = [UIImage imageNamed:image];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo-frame.png"]];
return cell;
}