UICollectionView类似我们常用的UITableView,但是还是有一些区别,就简单记录一下。
新建一个项目工程,打开StoryBoard,删除原有的控制器,选择CollectionVIewControl并拖到中间,从右边选择CollectionVIewControl

打开ViewController.h文件,把父类改为UICollectionViewController

打开VIewController.m文件,添加下面代码
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 80; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath]; cell.backgroundColor = [UIColor grayColor]; return cell; }
再打开StoryBoard,找到CollectionViewCell,添加Identifier标识

运行模拟器,结果如下图。

2、UICollectionView添加Header和Footer
打开StoryBoard,找到UICollectionView,把右边的Section Header和Section Footer勾上。

你就会看到在Cell的上面的下面多了View,这两个View就是Section Header和Section Footer

设计Section Header 和Section Footer的样式,Header添加ImageView和Label,Footer添加ImageView,并给Footer的ImageView设置图片

在Atteributes inspector中设置header view的identifier为“HeaderView”,同样的把footer view的identifier设置为“FooterView”。


添加Header View新类
因为在默认情况下,header和footer view和UICollectionResuable类相关联。为了在header view中显示我们需要的背景和标题,我们必须创建一个新的继承自UICollectionResuableView的类,我们可以命名为CollectionResuableHeaderView。


拖线

@interface CollectionResuableHeaderView :UICollectionReusableView @property(weak,nonatomic)IBOutlet UILabel *titleName; @property(weak,nonatomic)IBOutlet UIImageView *imageView; @end
实现viewForSupplementaryElementOfKind方法
打开VIewController.m文件,添加下面代码
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { static NSString *headerID = @"HeaderView"; static NSString *footerID = @"FooterView"; UICollectionReusableView *reusableView = nil; if (kind == UICollectionElementKindSectionHeader) { CollectionResuableHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerID forIndexPath:indexPath]; NSString *title = [[NSString alloc] initWithFormat:@"Group #%li",indexPath.section+ 1]; headerView.titleName.text = title; UIImage *headerImage = [UIImage imageNamed:@"head"]; headerView.imageView.image = headerImage; reusableView = headerView; }else if(kind == UICollectionElementKindSectionFooter){ UICollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerID forIndexPath:indexPath]; reusableView = footerview; } return reusableView; }
运行截图如下
