UICollectionView(集合视图) 的简单使用

本文介绍了UICollectionView在iOS开发中的基本使用,它与UITableView不同,能以更灵活的方式展示内容,如抽屉形式,适用于表情包选择、购物车等场景。通过设置多个节和单元格,实现丰富展示效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值