注冊(cè)CellId
static NSString *const XXCellId = @"XXCellId";
注冊(cè)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];
}
必須設(shè)置的布局
- (instancetype)init;
- (instancetype)init{
// 設(shè)置流水布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake(100, 100);
// 設(shè)置最小行間距
layout.minimumLineSpacing = 2;
// 設(shè)置最小垂直間距
layout.minimumInteritemSpacing = 2;
// 設(shè)置滾動(dòng)方向(默認(rèn)垂直滾動(dòng))
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
return [self initWithCollectionViewLayout:layout];
}
定義展示的Section的個(gè)數(shù)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 2;
}
定義展示的UICollectionViewCell的個(gè)數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return 3;
}
定義每個(gè)UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(80, 80);
}
定義每個(gè)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 為水平滑動(dòng)時(shí),間距有效鲫构。height 為垂直滑動(dòng)時(shí),間距有效。
return CGSizeMake( width,height );
}
區(qū)頭 ? 與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;
}
是否允許選中 默認(rèn)否
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
選中的狀態(tài)
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}