@implementation HomeViewController
//定义重用标识符
static NSString *identifier = @"collectionCell";
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
/*
collectionView 必须有一个layout
在storyboard上拖拽的时候,已经自动增加一个 流水布局
UICollectionView must be initialized with a non-nil layout parameter
实例化一个layout对象:collectionView如果要实例化一个layout,必须在实例化的时候就进行设置
UICollectionViewLayout 是流水布局的父类,是最纯净的layout
UICollectionViewFlowLayout 在父类上做了扩展
*/
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
//修改cell的大小 默认宽高为50
flowLayout.itemSize = CGSizeMake(100, 100);
//实例化一个collectionView
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
[self.view addSubview:collectionView];
//设置代理
collectionView.dataSource = self;
collectionView.delegate = self;
//注册一个collectionCell
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:identifier];
//设置背景色
collectionView.backgroundColor = [UIColor whiteColor];
}
//组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 100;
}
//每一行的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//从缓存池中去找
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
return cell;
}
//取消选中
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"取消选中 - %ld",indexPath.item);
}
//被选中
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//item 相当于row
NSLog(@"选中 - %ld",indexPath.item);
}