UICollectionViwe的基本使用

collectionView的使用于UITableView的使用类似,但是collectionview没有表头与表尾,只有组头与组尾,同时在设置items的size时需要使用flowLayout进行设置,同时也可以通过UICollectionViewDelegateFlowLayout中的代理方法设置每一个行的组头与组尾的高度

1.创建flowLayout

- (void)prepareLayout{
    [super prepareLayout];
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.minimumLineS
    pacing = 1;//跟滚动方向相同的间距
    self.minimumInteritemSpacing = 1;//跟滚动方向垂直的间距
    self.sectionInset = UIEdgeInsetsMake(0, 0, 20, 0);
}

2.注册cell,同tableView一样,有几种cell就注册几种cell
3.根据需求注册headerViwe与footerView

   [collectionView registerClass:[GGAutoCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerCellID];
   [collectionView registerClass:[GGAutoCollectionFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerCellID];

注意组头与组尾视图都是继承UICollectionReusableView

@interface GGAutoCollectionHeaderView : UICollectionReusableView

4.设置组头与组尾的高度可以根据layout进行设置

  ZFBBusinessTypeLayout *layout = [[ZFBBusinessTypeLayout alloc]init];
    //设置组头组尾的高度
  layout.headerReferenceSize = CGSizeMake(CGRectGetWidth(self.frame), 20); 
   layout.footerReferenceSize = CGSizeMake(CGRectGetWidth(self.frame), 20);

5.或者使用代理方法设置组头与组尾的高度

//以下方法是在UICollectionViewDelegateFlowLayout中
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if(section == 0)
        return CGSizeMake(CGRectGetWidth(self.frame), 220);
    return CGSizeMake(CGRectGetWidth(self.frame), 10);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if(section == 0)
          return CGSizeMake(CGRectGetWidth(self.frame), 220);
      return CGSizeMake(CGRectGetWidth(self.frame), 10);
}

6.添加组头与组尾 (组尾同下)

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if([kind isEqualToString:UICollectionElementKindSectionHeader]){
    if(indexPath.section == 0){
        GGTopReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID forIndexPath:indexPath];
        return headerView;
    }
    GGTopReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID forIndexPath:indexPath];
    headerView.delegate = self;
    return headerView;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容