UICollectionView與UITableView一樣都需要遵從代理和數(shù)據(jù)源的方法。
1.UICollectionView 創(chuàng)建之前需要先寫布局俺亮,每個collection都需要遵從這個布局艰争。
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
CGFloat itemW = kScreenWidth/3;
CGFloat itemH = 0.85*itemW + 20;
layout.itemSize = CGSizeMake(itemW, itemH);
layout.headerReferenceSize = CGSizeMake(0, 10); //頭視圖的大小參數(shù)
layout.minimumInteritemSpacing = 0;
layout.minimumLineSpacing = 0; // cell 間距
2.然后注冊頭視圖
[_collection registerClass:[UICollectionReusableViewclass] forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:@"header"];
3.代理方法
//創(chuàng)建collection頭視圖
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
header.backgroundColor = ZJColorFromRGB(0xf6f6f6);
return header;
}
// 設(shè)置section頭視圖的參考大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
return CGSizeMake(kScreenWidth, 10);
}
如果需要自定義頭視圖實現(xiàn)具體功能灵份,可以繼承UICollectionReusableView來實現(xiàn)剑刑。