collectionview的代码自定义和初始化

本文介绍如何使用 UICollectionViewFlowLayout 初始化 UICollectionView,并实现自定义 UICollectionViewCell 的过程。包括 UICollectionView 的基本配置、重用 UICollectionViewCell 的代码、清除自定义 CollectionViewCell 中的子视图以避免重复显示,以及设置 cell 高度的方法。

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


  1.   /**UICollectionView的初始化*/

    UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];

    UICollectionView * _colview=[[UICollectionView alloc] initWithFrame:CGRectMake(0,0,width,height) collectionViewLayout:layout];

    _colview.backgroundColor=[UIColor whiteColor];

    [self.mainsclview addSubview:_colview];


    [_colview registerClass:[FirstCollectionCell class]

 forCellWithReuseIdentifier:@"Cell"];

    _colview.delegate=self;

    _colview.dataSource=self;

 2.实现delegate的方法-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath中添加重用代码

static NSString * CellIdentifier = @"Cell";

    FirstCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];


3.如果是自定义Collectionviewcell,记住要先添加

    for (UIView *v  in cell.contentView.subviews)   

    {

        [v removeFromSuperview];

    }

或者

    for (UIView *v  in cell.contentView.subviews)   

    {

        [v removeFromSuperview];

    }

取决于你讲子视图添加进去cell,还是cell.contentview中。这样才不回出现往复出现。

4.在

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 中设置cell的高度。



5.如果是自定义的collectioncell类酒不用第三部这么麻烦


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值