[OC] UIcollectionView 与 UIcollectionViewCell 的使用

本文介绍如何使用UICollectionView展示数据,包括UICollectionViewFlowLayout布局参数设置、cell注册与重用、代理方法实现等关键技术点。

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

  UICollectionView

  

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

@end

//collectionView布局初始化
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
//定义每个Cell 的大小
flowLayout.itemSize = CGSizeMake(280, 280);
//头部大小
flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 40);
//定义每个Cell 纵向的间距
flowLayout.minimumLineSpacing = 10;
//定义每个Cell 横向的间距
flowLayout.minimumInteritemSpacing = 20;
//定义每个Cell到容器边缘 的边距
flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);//上左下右
    
//collectionView初始化
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
//注册cell
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//设置代理
_collectionView.delegate = self;
_collectionView.dataSource = self;
//背景颜色
_collectionView.backgroundColor = [UIColor greenColor];
//自适应大小
_collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//界面添加
[self.view addSubview:_collectionView];
//尺寸设置
[_collectionView setFrame:self.view.frame];
//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

//每个cell展示的内容的具体实现
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //注意单元格复用,注意identifier和之前注册时用的相同(@"cell")
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[UICollectionViewCell alloc] init];
    }
    return cell;
}

//cell被选中时触发
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"你点了一个单元格");
}

 

新建的UIcoolectionViewCell文件中放入这一句进行初始化:

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self)
    {
        //在这里写入对cell进行定制的内容
    }
    return self;
}

 

转载于:https://www.cnblogs.com/OranBlog/p/9208782.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值