collectionview resueview 重影的问题

本文探讨了使用UICollectionView实现分区效果时出现的重影问题。分析了错误代码导致该问题的原因,并提供了修正后的代码实现,确保了每个分区头部正确显示且避免了重影现象。

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

        现在好多学生使用UICollectionView来呈现视图展示,但是在使用UICollectionReusableView来做分区效果的时候,很容易造成重影效果,其造成重影的原因是,在重用的UICollectionReusableView上面一直添加视图,而重用的UICollectionReusableView在重用时,又重新创建了一个,而原来的还在。这个时候就会造成重影效果。先给大家看一下错误的代码:
[Objective-C]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:( NSString *)kind atIndexPath:( NSIndexPath *)indexPath
{
     UICollectionReusableView * reusable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier: @"header" forIndexPath:indexPath];
     
      UILabel * titLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 15, 200, 30)];
     [reusable addSubview:titLabel];
     titLabel.text = [_headerArr objectAtIndex:indexPath.section];
     [titLabel release];
       return reusable;
}

正确的代码
[Objective-C]  纯文本查看  复制代码
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:( NSString *)kind atIndexPath:( NSIndexPath *)indexPath
{
     UICollectionReusableView * reusable = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier: @"header" forIndexPath:indexPath];
     
 
     UILabel * titLabel = (UILabel *)[reusable viewWithTag:1000];
     if (!titLabel)
     {
         titLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 15, 200, 30)];
         titLabel.tag=1000;
     }
     [reusable addSubview:titLabel];
     titLabel.text = [_headerArr objectAtIndex:indexPath.section];
     return reusable;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值