#import "ViewController.h"
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1.瀑布流
UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
// 2.设置大小
flowLayout.itemSize = CGSizeMake(50, 50);
// 3.设置方向
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
// 4.设置item间隔
//设置每组的item(如果是垂直显示 行距。如果是水平方向显示 列距)
flowLayout.minimumLineSpacing = 20;
// 设置 每组item(如果是垂直显示 列距。如果是水平方向显示 行距)
flowLayout.minimumInteritemSpacing = 20;
// 设置每组距离上左下右的距离
flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
// 5.设置代理和数据源方法
collectionView.delegate = self;
collectionView.dataSource = self;
collectionView.backgroundColor = [UIColor lightGrayColor];
// 6.item注册
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"ID"];
[self.view addSubview:collectionView];
}
// 实现代理方法 1. 确定collection一共有几组
- (NSInteger )numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 4;
}
// 实现代理方法 2. 确定每一组collection一共有几个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 7;
}
//实现代理方法 3.确定每一个cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSString *ID = @"ID";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor redColor];
return cell;
}
//实现代理方法 4.确定点击cell时要进行什么操作
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// 进行的操作:打印cell所点击cell的Section的索引和row索引
NSLog(@"%ld --- %ld",indexPath.section, indexPath.row);
}
效果图

原文:http://www.cnblogs.com/fanwenzheIOS/p/4982924.html