UICollectionView的基本使用

一:创建:

      必须要有一个UICollectionViewLayout来初始化,通常使用UICollectionViewFlowLayout流布局就可以了,有需要就自定义UICollectionViewLayout(比较复杂)。

二:关于cell:

1.全局的重用标识符identifier:cell需要,UICollectionReusableView也需要。

2.注册cell:

    a. 注册代码自定义的cell:

// 注册cell

 [_collectionView_ registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:identifier];

// 注册UICollectionReusableView

[_collectionView_ registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];

[_collectionView_ registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];


     b.注册xib写的cell:

[_collectionView_ registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:nil] forCellWithReuseIdentifier:identifier];

3.生成cell:

CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

只需要这个方法,就可以生成cell,且不需要判断cell是否存在,如果cell不存在,会自己去生成,然后操作cell的内容就好了。加载xib的cell也是这个方法,这就是与UITableView的区别。

4.cell的大小:遵循UICollectionViewDelegateFlowLayout协议

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

cell之间的间距什么的也都在这个协议的方法内设置。

其余的代理方法与UITableView类似。

三:其他:

a. 设置collectionView横向滑动:

layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

b.设置collectionView不可弹回

collectionView.bounces = NO;

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

推荐阅读更多精彩内容