collectionView的使用于UITableView的使用類似磕道,但是collectionview沒(méi)有表頭與表尾,只有組頭與組尾舞竿,同時(shí)在設(shè)置items的size時(shí)需要使用flowLayout進(jìn)行設(shè)置,同時(shí)也可以通過(guò)UICollectionViewDelegateFlowLayout中的代理方法設(shè)置每一個(gè)行的組頭與組尾的高度
1.創(chuàng)建flowLayout
- (void)prepareLayout{
[super prepareLayout];
self.scrollDirection = UICollectionViewScrollDirectionVertical;
self.minimumLineS
pacing = 1;//跟滾動(dòng)方向相同的間距
self.minimumInteritemSpacing = 1;//跟滾動(dòng)方向垂直的間距
self.sectionInset = UIEdgeInsetsMake(0, 0, 20, 0);
}
2.注冊(cè)cell,同tableView一樣缤灵,有幾種cell就注冊(cè)幾種cell
3.根據(jù)需求注冊(cè)headerViwe與footerView
[collectionView registerClass:[GGAutoCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerCellID];
[collectionView registerClass:[GGAutoCollectionFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerCellID];
注意組頭與組尾視圖都是繼承UICollectionReusableView
@interface GGAutoCollectionHeaderView : UICollectionReusableView
4.設(shè)置組頭與組尾的高度可以根據(jù)layout進(jìn)行設(shè)置
ZFBBusinessTypeLayout *layout = [[ZFBBusinessTypeLayout alloc]init];
//設(shè)置組頭組尾的高度
layout.headerReferenceSize = CGSizeMake(CGRectGetWidth(self.frame), 20);
layout.footerReferenceSize = CGSizeMake(CGRectGetWidth(self.frame), 20);
5.或者使用代理方法設(shè)置組頭與組尾的高度
//以下方法是在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;
}