UICollectionView 是沒有類似于UITableview的整體表頭的,在注冊cell時,如果分區(qū)表頭,表尾也需要注冊,如果有個需求:只是簡單給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];
分區(qū)表頭表尾有時候設置了代理代理方法不走,是因為分區(qū)表頭表尾的size沒有設置,有兩種方法,
一:設置 flowLayout.headerReferenceSize = CGSizeMake(KScreenW, 100);
flowLayout.headerReferenceSize = CGSizeMake(KScreenW, 100);
二:設置代理方法里 可針對單獨分區(qū)進行設置;
- (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;
}