文章目录
前言
UICollectionView
和UICollectionViewController
类是iOS6 新引进的API,用于展示集合视图,布局更加灵活,可实现多列布局,用法类似于UITableView
和UITableViewController
类。- 使用
UICollectionView
必须实现UICollectionViewDataSource
,UICollectionViewDelegate
,UICollectionViewDelegateFlowLayout
这三个协议。
UICollectionView
是比UITableView
更加强大的一个UI控件,有如下几个方面:
- 支持水平和垂直两种方向的布局
- 通过
layout
配置方式进行布局 - 类似于
TableView
中的cell
特性外,CollectionView
中的item
大小和位置可以自由定义 - 通过
layout
布局回调的代理方法,可以动态的定制每个item
的大小和collection
的大体布局属性 - 更加强大一点,完全自定义一套
layout
布局方案,可以实现意想不到的效果
九宫格类布局
- 可以先制作一个最简单的九宫格动画
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//创建一个layout布局类
UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
//设置布局方向为垂直流布局
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//设置每个item的大小为100*100
layout.itemSize = CGSizeMake(100, 100);
//创建collectionView 通过一个布局策略layout来创建
UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
//代理设置
collect.delegate = self;
collect.dataSource = self;
//注册item类型 这里使用系统的类型
[collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
[self.view addSubview:collect];
}
这里有一点需要注意,collectionView
在完成代理回调前,必须注册一个cell
,类似如下:
[collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
这和tableView
有些类似,又有些不同,因为tableView
除了注册cell
的方法外,还可以通过临时创建来做:
//tableView在从复用池中取cell的时候,有如下两种方法
//使用这种方式如果复用池中无,是可以返回nil的,我们在临时创建即可
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
//6.0后使用如下的方法直接从注册的cell类获取创建,如果没有注册 会崩溃
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *