UICollectionViews是一个集合视图与uitableview使用方法十分相似,但是展示的效果却并不相同,uitableview是一行行显示且可以分组,但是uicollectionView是可以以抽屉的形式显示,这之中分为多个节,每个节之中有多个单元格,这个控件十分的有用,可以用来做出表情包选择的效果,还可以做出购物车添加效果等等。
基本使用代码如下
//1、创建流式布局(从上到下,从左到右的布局)
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
//2、设置每个单元格的尺寸
layout.itemSize = CGSizeMake(80, 80);
//3、设置整个collectionView的内边距
layout.sectionInset = UIEdgeInsetsMake(70, 40, 10, 10);
//4、设置单元格之间的最小间距
layout.minimumLineSpacing = 10;
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout];
//5、设置可重用单元格标识与单元格类型
[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
self.collectionView.backgroundColor = [UIColor whiteColor];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
[self.view addSubview:self.collectionView];
#pragma mark collectionView dataSource
//提供视图中节的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 2;
}
//提供视图中某个节的列数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 3;
}
//为某个单元格提供显示数据
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor blueColor];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
label.text = [NSString stringWithFormat:@"%ld",indexPath.row];
label.backgroundColor = [UIColor orangeColor];
[cell.contentView addSubview:label];
return cell;
}
//选择单元格后触发
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"%ld",indexPath.row);
NSLog(@"%ld",indexPath.section);
}
显示效果如下
image.png
网友评论