平常我在业务开发中,绝大部分情况都是使用的UITableView,而UICollectionView则是在极少情况下才会去使用,这就导致了我对UICollectionView略感陌生。本篇文章就是以二者对比的方式对UICollectionView做一个小总结。
UICollectionView的collectionCell支持横向&纵向布局,比UITableView的tableCell只有纵向布局要更加灵活。
UICollectionView和UITableView有相同的API设计理念——都是基于dataSource以及delegate驱动的。
UITableView中的row,对应到UICollectionView中就是item,因为一行可以展示多个cell,使用row(行)不能准确地表达。
例如,UITableView中的如下代理方法:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
对应到UICollectionView的代理方法中就是:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
我们知道,UITAbleViewCell是有四种默认样式的,但是UICollectionViewCell是没有默认样式的,所有的控件都需要自定义添加到contentView上。
UITableView获取cell:
方式一:先注册,然后直接deque获取;
方式二:不用注册,dequeue+判断获取。
而UICollectionViewCell的获取,必须是先注册,然后通过dequeue方法获取。
系统默认给我们提供了一种layout——UICollectionViewFlowLayout。UICollectionViewFlowLayout的设计理念就是,item现在一行中依次排列,一行满了之后就换一行接着排列剩余的Item。其有三个比较重要的属性:minimumInteritemSpacing设置一行中两个Item之间的最小间距,minimumLineSpacing设置上下两行之间的最小间距,itemSize设置每一个item的尺寸。
通过UICollectionViewFlowLayout中的itemSize属性是将所有的Item都设置成一个统一的样式,如果我们需要对特定的item进行自定义样式,那么就需要实现UICollectionViewDelegateFlowLayout中的代理方法:
@protocol UICollectionViewDelegateFlowLayout <UICollectionViewDelegate>
@optional
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
@end
layout可以用来定义每一个item的布局,这是UITableView和UICollectionView的最大的不同。
UICollectionViewLayout是一个抽象类,上面我讲了UICollectionViewFlowLayout,它是系统为我们提供的继承自UICollectionViewLayout的用于流式布局的layout,如果我们想要实现一个自定义的布局,那么就新建一个继承自UICollectionViewLayout的子类,然后去自定义。
以上。