1.初始化UICollectionView
-(void)initCollectionView{
UICollectionViewFlowLayout * flowl=[[UICollectionViewFlowLayout alloc]init];
//flowl.minimumLineSpacing=10;
//flowl.minimumLineSpacing=10;
flowl.scrollDirection=UICollectionViewScrollDirectionVertical;
_collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20) collectionViewLayout:flowl];
_collectionView.delegate=self;
_collectionView.dataSource=self;
_collectionView.backgroundColor=[UIColor orangeColor];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
[self.view addSubview:_collectionView];
}
2.实现UICollectionView 的协议的三个必须方法
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//定义展示的UICollectionViewCell 的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 20;
}
//每个UICollectionViewCell 展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString * identifier=@"UICollectionViewCell";
UICollectionViewCell * cell1=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell1.backgroundColor=[UIColor blueColor];
UILabel * label=[[UILabel alloc]initWithFrame:CGRectMake(10,10 ,60, 30)];
label.text=[NSString stringWithFormat:@"-----%ld",indexPath.row];
label.font=[UIFont systemFontOfSize:16];
for(id subView in cell1.contentView.subviews){
[subView removeFromSuperview];
}
[cell1.contentView addSubview:label];
return cell1;
}
3.实现UICollectionViewDelegateFlowLayout协议的方法//定义每个Item的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake((KDeviceWidth-40)/2, 100);
}
//定义每个UICollectionViewCell 的margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(5, 5, 5, 5);
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
//返回这个UICollectionView是否可以被选择
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
NSLog(@"%ld--%ld-%ld",(long)indexPath.item,indexPath.section,indexPath.row);
}