CollectionView Header的使用

岑叶秋
2023-12-01

 collectionView的使用和tableView类似,遵守数据源和代理方法是必要的,而不太常用的是 CollectionView Header,如果你想给每一组section设置不同的cell也是也可行的

遵守下面的代理方法:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        if (self.attentionDataArr.count == 0) {
            PlaceholderView *placeHeader = (PlaceholderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:PlaceheaderIdentifier forIndexPath:indexPath];
            if (self.hasAttentionPeople == 1) {
                placeHeader.placeholdLabel.text = NSLocalizedString(@"HOME_ATTATENT_PLACEHOLDER_NULLLIVE_TIP", nil);
            }else if (self.hasAttentionPeople == 2) {
                placeHeader.placeholdLabel.text = NSLocalizedString(@"HOME_ATTATENT_PLACEHOLDER_NULLFOLLOW_TIP", nil);
            }
            return placeHeader;
        }else{
            return nil;
        }
    }else{
        AttenttionCellHeaderView *attentionHeaderView  = (AttenttionCellHeaderView*)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        return attentionHeaderView;
    }
    
}

每个headerView的高度,用以下方法返回

//这个方法是返回 Header的大小 size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{

        if (section == 0) {
            if (self.attentionDataArr.count == 0) {
                return CGSizeMake(kScreenWidth, 429 * ScreenHeightRatio);
            }
            return CGSizeZero;
        }else{
            return CGSizeMake(kScreenWidth, self.headerH);
        }
    
}


就可以了,使用什么headerView记得要事先注册

[self.myCollectionView registerClass:[AttenttionCellHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier]; 


[self.myCollectionView registerClass:[PlaceholderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:PlaceheaderIdentifier];




 footer和header用法是一样的。
 类似资料: