UICollectionView图像重新出现在单元格上

时间:2015-02-25 03:43:22

标签: objective-c uicollectionview

我使用以下代码将数组中的图像添加到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。

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

请知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

因为你正在使用细胞回收的东西,所以当一个细胞返回给你重复使用时你应该删除(或重复使用)任何旧的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; 

}