注册CellId
static NSString *const XXCellId = @"XXCellId";
注册Cell
[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([XXCell class]) bundle:nil] forCellWithReuseIdentifier:XXCellId];
初始化&赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
XXCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:XXCellId forIndexPath:indexPath];
cell.cellData = [[[self.XXModel.xxx objectAtIndex:indexPath.section] yyy] objectAtIndex:indexPath.item];
}
必须设置的布局
- (instancetype)init;
- (instancetype)init{
// 设置流水布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake(100, 100);
// 设置最小行间距
layout.minimumLineSpacing = 2;
// 设置最小垂直间距
layout.minimumInteritemSpacing = 2;
// 设置滚动方向(默认垂直滚动)
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
return [self initWithCollectionViewLayout:layout];
}
定义展示的Section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 2;
}
定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 3;
}
定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(80, 80);
}
定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(5, 10, 5, 10);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
width 为水平滑动时,间距有效。height 为垂直滑动时,间距有效。
return CGSizeMake( width,height );
}
区头 与cell大概相同
static NSString *const HeaderViewId = @"HeaderViewId";
[self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([HeaderView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderViewId];
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
HeaderView *HeaderView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderViewId forIndexPath:indexPath];
return HeaderView;
}
是否允许选中 默认否
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
选中的状态
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}