1、概述android
UICollectionView控件主要是用来作九宫格的,相似于android中的GridView控件。其用法与UITableView同样,首先要使控制器遵照数据源协议,再将控制器设置为UICollectionView的数据源。一样,控制器遵照了UICollectionView的代理后也能够实现代理方法等。缓存
2、经常使用的数据源方法布局
设置UICollectionViewController一共有多少组:atom
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView代理
*)collectionView;事件
设置每组有多少单元格:ci
- (NSInteger)collectionView:(UICollectionView *)collectionViewit
numberOfItemsInSection:(NSInteger)section;io
设置每一个单元格显示的内容:class
- (UICollectionViewCell *)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
3、经常使用的代理方法
设置每一个单元格点击事件:
- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
MJProduct *p = self.products[indexPath.item];
NSLog(@"点击了---%@", p.title);
}
4、UICollectionViewController必须调用的方法
(1)注册cell(告诉collectionView未来建立怎样的cell)
[self.collectionView registerClass:[UICollectionViewCell class]
forCellWithReuseIdentifier:@"product"];
在调用- (UICollectionViewCell *)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;设置每一个单元格显示的内容(UICollectionViewCell)以前必须注册cell,通常在viewDidLoad中调用上面方法注册cell。
例如:
- (void)viewDidLoad
{
[super viewDidLoad];
// 1.注册cell(告诉collectionView未来建立怎样的cell)
UINib *nib = [UINib nibWithNibName:@"MJProductCell" bundle:nil];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:
MJProductCellID];//经过xid自定义的cell
/*
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:MJProductCellID];//使用默认的UICollectionViewCell
*/
// 2.设置collectionView的背景色
self.collectionView.backgroundColor = [UIColor whiteColor];
}
(2)从缓存池中取出cell
- (UICollectionViewCell *)collectionView:(UICollectionView
*)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell =
[collectionView dequeueReusableCellWithReuseIdentifier:@"product" forIndexPath:indexPath];
return cell;
}
在从缓存池取UICollectionViewCell重用时,不用再判断缓存池是否为空了,它与UITableView不一样的是UICollectionView在缓存池没有找到cell时会自动建立新的cell。
(3)重写init方法,建立布局参数
- (id)init
{
// 1.流水布局
UICollectionViewFlowLayout *layout =
[[UICollectionViewFlowLayout alloc] init];
// 2.每一个cell的尺寸
layout.itemSize = CGSizeMake(80, 80);
// 3.设置cell之间的水平间距
layout.minimumInteritemSpacing = 0;
// 4.设置cell之间的垂直间距
layout.minimumLineSpacing = 10;
// 5.设置全部cell组成的一个总体与屏幕(ViewController)四周距离
layout.sectionInset =
UIEdgeInsetsMake(layout.minimumLineSpacing, 0, 0, 0);
return [super initWithCollectionViewLayout:layout];
}
若是不建立布局参数程序会报错。通常在重写控制器的init方法中建立。
5、UICollectionViewFlowLayout
UICollectionViewFlowLayout称为”流水布局”, 用来约束cell的显示。
常见属性:
Cell的尺寸:
@property (nonatomic) CGSize itemSize;
cell之间的水平间距:
@property (nonatomic) CGFloat minimumInteritemSpacing;
cell之间的垂直间距:
@property (nonatomic) CGFloat minimumLineSpacing;
四周的内边距:
@property (nonatomic) UIEdgeInsets sectionInset;