【问题标题】:UICollectionView image re-appears on cellUICollectionView 图像重新出现在单元格上
【发布时间】:2015-02-25 03:43:22
【问题描述】:

我使用以下代码将图像从数组添加到 uicollectionview 单元格。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    UIImageView *emoji = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    emoji.image = [UIImage imageNamed:[imagePack objectAtIndex:indexPath.row]];
    emoji.contentMode = UIViewContentModeScaleAspectFit;
    [cell.contentView addSubview:emoji];

    return cell;
}

当我向下滚动 UICollectionView 然后向上滚动时,图像会重新出现在每个单元格的顶部。假设我有单元格 1 的图像 1,单元格 2 的图像 2,依此类推。如果我向下滚动然后向上滚动,在单元格 1 中我有图像 1,图像 1 的顶部是图像 2。

在我滚动之后,它会弄乱图像,在滚动看起来正常之前。

请知道我做错了什么?

【问题讨论】:

    标签: objective-c uicollectionview


    【解决方案1】:

    因为您使用的是细胞回收材料,所以当一个细胞返回给您以供重复使用时,您应该删除(或重用)任何旧的 imageView 试试这样的..

        -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
        UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    
        UIImageView *emoji = nil;
    
          //try to find old imageView
         for (UIView *vw in cell.contentView.subviews){
            if ([vw isKindOfClass:[UIImageView class] ]){
              emoji = (UIImageView *)vw;
            }
          }
    
        if (emoji==nil){
       //we failed to find an imageView...
    
            emoji = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
            [cell.contentView addSubview:emoji];
            //creating a UIImageView only if one is not already there
        }else{
        emoji.frame = CGRectMake(0, 0, 50, 50);
        }
    
       emoji.image = [UIImage imageNamed:[imagePack objectAtIndex:indexPath.row]]; 
       emoji.contentMode = UIViewContentModeScaleAspectFit; 
    
    
        return cell; 
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多