<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout >
//创建布局对象 UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; //设置单元格的尺寸 flowLayout.itemSize = CGSizeMake(80, 80); //设置头视图高度 flowLayout.headerReferenceSize = CGSizeMake(0, 30); //flowlaout的属性,横向滑动 flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; //接下来就在创建collectionView的时候初始化,就很方便了(能直接带上layout) _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, 320, 280) collectionViewLayout:flowLayout]; _myCollectionView.tag = 200; _myCollectionView.backgroundColor = [UIColor greenColor]; _myCollectionView.delegate = self; _myCollectionView.dataSource = self; //添加到主页面上去 [self.view addSubview:_myCollectionView]; //collectionCell的注册 [_myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"myheheIdentifier"]; //collection头视图的注册 奇葩的地方来了,头视图也得注册 [_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Identifierhead”]; #pragma mark -UICollectionViewDataSource //指定组的个数 ,一个大组!!不是一排,是N多排组成的一个大组(与下面区分) - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 2; } //指定单元格的个数 ,这个是一个组里面有多少单元格,e.g : 一个单元格就是一张图片 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 10; } //构建单元格 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { if (collectionView.tag == 200) { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myheheIdentifier" forIndexPath:indexPath]; cell.backgroundColor = [UIColor purpleColor]; return cell; } } //组的头视图创建 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Identifierhead" forIndexPath:indexPath]; headView.backgroundColor = [UIColor blueColor]; return headView; } //通过协议方法设置单元格尺寸 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { CGFloat rd = arc4random()%90; return CGSizeMake(90, rd); }
原文:http://blog.csdn.net/u013243469/article/details/44595961