UICollectionViewController的简单使用

注册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{

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容