UICollectionView是布局瀑布流的方法,首先介绍该控件的基本使用状况
首先继承代理
划线的是唯一标示符
//UICollectionView在初始化时候,必须传递一个非空得layout参数
/*
第一个参数:UICollectionView的尺寸
第二个参数:UICollectionView的布局对象
*/
//布局对象:布局对象的作用就是用于控制UICollectionView中所有的子控件排布(cell,补充视图,装饰视图)
//UICollectionViewLayout 基类,根布局,内部默认没有任何排布,所有子控件如何排布都需要我们自己编码排布实现
// UICollectionViewFlowLayout 流水布局,默认是从左到右,一个接一个的布局
//1.创建UICollectionView
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
//设置每个格子宽高100
layout.itemSize=CGSizeMake(100, 100);
//设置垂直间隙
//设置水平间隙
//设置顶部的扩展区域
//设置底部的扩展区域
//设置四周的扩展区域
//设置滚动方向
// 上面属性点进去可以查看
UICollectionView *clView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
clView.backgroundColor=[UIColor whiteColor];
// clView.frame=self.view.frame;
//在成为数据源之前,告诉系统通过哪一个类来创建UICollectionViewCell
[clView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];
//设置UICollectionView的数据源为当前控制器
clView.dataSource=self;
clView.delegate=self;
[self.view addSubview:clView];
下面是数据源方法和代理方法
#pragma mark -dataSource
//告诉UICollectionView 一共多少组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//告诉UICollectionView 每一组中需要展示多少个小方块
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 5;
}
//告诉系统 每个小方块展示什么内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//1.从缓存池中获取cell
UICollectionViewCell *cell= [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
//UICollectionViewCell和UITableViewCell的区别UICollectionView的dequeueReusableCellWithReuseIdentifier这个方法如果去缓存池中去取,没有取到cell,那么该方法内部会自动创建一个cell 但是需要注意的是:通过哪一类来创建cell必须由我们来制定
cell.backgroundColor=[UIColor redColor];
return cell;
}
//点击小方块执行的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%s",__func__);
}