美文网首页
UICollectionView的基本用法

UICollectionView的基本用法

作者: 2f976237cee2 | 来源:发表于2017-06-04 21:20 被阅读72次

最近因为写了个UICollectionView的控件,本来可以很快完成的,但是因为种种忘了使用方法,浪费了不少时间,在本周总结上,记录一下UICollectionView的用法,也请各位多多指教。

在此先附上官方文档UICollectionView官方文档

首先,从初始化开始,UICollectionView的初始化需要加入UICollectionViewFlowLayout ,不然系统不会让你初始化成功的,如果不是需要自定义UICollectionViewCell 的位置或者有所计算的话,可以直接使用系统自带,但建议自定义flowLayout继承自UICollectionViewFlowLayout,谁知道以后需求设计会不会突然让你改呢,下面是collectionView的初始化,我自定义了一个layout,但因为没有做什么操作,所以这里就没有列出来。

CustomCollectionView *collectionView = [[CustomCollectionView alloc] initWithFrame:CGRectMake(0, 0, DefaultWidth, DefaultHeight) collectionViewLayout:[CustomCollectionViewLayout new]];

但还是要小小的附上一段使用layout的方法,重写layoutAttributesForElementsInRect方法,即可更改每个item的frame:


- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {

NSArray * attributes = [[NSArray alloc] initWithArray:[super layoutAttributesForElementsInRect:rect] copyItems:YES];

for (UICollectionViewLayoutAttributes *attr in attributes) {

CGRect frame = attr.frame; //这里的attr可取出frame也可重新为其赋值

}

return attributes;

}

以上说完了初始化,接下来是使用。UICollectionView的item都是一个单元格,每个item的大小以及位置都可以动态改变或者赋予固定值出现。若使用固定值,则在flowLayout的定义时便可以设置。

flowLayout.itemSize = CGSizeMake(44,44); //设置Item的size
flowLayout.minimumLineSpacing = 0; //设置行间距
flowLayout.minimumInteritemSpacing = 0; //设置列间距

若想动态更改每个item的大小或位置,则使用上面提到的layoutAttributesForElementsInRect
方法。

当然,若自定义flowLayout但是没有赋值给UICollectionView的话,对于UICollectionView来说,并没有什么item更改的意义,所以:

(UICollectionView *).collectionViewLayout = flowLayout;

也别忘了UICollectionView必须设置的代理

(UICollectionView *).dataSource = self;

(UICollectionView *).delegate = self;


当然,要使用collectionView少不了它的代理方法:

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

return 1;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

return self.dataArray.count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(self.class) forIndexPath:indexPath];

cell.user = self.dataArray[indexPath.item];

return cell;

}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}

没错,跟UITableView的代理如出一辙,相信不需要说明都可以理解。

以上是UICollectionView的基本使用方法,在下仅是简单记录说明一下,以后会每周陆续更新一些自己用到的本应该很快完成,但却因为忘了基本用法卡壳的一些东西。

相关文章

网友评论

      本文标题:UICollectionView的基本用法

      本文链接:https://www.haomeiwen.com/subject/sdofmttx.html