介绍:
提供灵活的、可定制的列表类型的视图组件、列表功能「点击删除、插入以及布局的切换」、提供默认基础的flow样式布局以及cell的复用回收逻辑。
区别UITableView:
基本使用:
- 创建UICollectionViewLayout,使用系统默认流式布局或者自定义布局。
- 创建UICollectionView,设置delegate和datasource,注册cell类型。
- 选择实现UICollectionDataSource中的方法。
- 选择实现UICollectionDelegate中的方法。
代码演示:
#import "JKVideoVc.h"
@interface JKVideoVc ()<UICollectionViewDelegate,UICollectionViewDataSource>
@end
@implementation JKVideoVc
- (void)viewDidLoad {
[super viewDidLoad];
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 10;
layout.itemSize = CGSizeMake((self.view.frame.size.width-10)/2, 300);
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
collectionView.delegate = self;
collectionView.dataSource = self;
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
[self.view addSubview:collectionView];
// Do any additional setup after loading the view.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 20;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
if(indexPath.item % 3 == 0){
return CGSizeMake(self.view.frame.size.width, 300);
}else{
return CGSizeMake((self.view.frame.size.width-10)/2, 100);
}
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
cell.backgroundColor = UIColor.redColor;
return cell;
}
@end