UICollectionView重复单元格

时间:2013-10-12 18:05:11

标签: iphone ios uicollectionview uicollectionviewcell

我有UICollectionView,其中显示从互联网下载的图像网格。我正在使用SDWebImage加载图片。我面临的问题是,当我滚动UICollectionView时,有时单元格会重复,显示相同的图像。但是当单元格滚出视图然后返回时,它具有正确的图像集。

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

    NSString *CellIdentifier = @"Gallery_Cell";

    GalleryCell *cell;

    if (cell==nil) {
        cell= (GalleryCell *)[self.flowCollection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

        ImageItem *dets = [self.imageList objectAtIndex:indexPath.row];

        NSURL *mainImageURL = [NSURL URLWithString:dets.smallImageURL];

        cell.image.contentMode = UIViewContentModeScaleAspectFill;
        cell.image.clipsToBounds = YES;                

        [cell.image setImageWithURL:mainImageURL placeholderImage:nil];

    }

    return cell;

}

这是否发生在其他人身上?非常感谢任何指针。

6 个答案:

答案 0 :(得分:7)

GalleryCell.m上,您需要添加prepareForReuse方法并取消_image变量(假设您在单元格中有image @property):

- (void)prepareForReuse {
    [super prepareForReuse];
    [self setHighlighted:NO];

    _image = nil;
}

答案 1 :(得分:5)

“UICollectionView类参考”中说明了以下内容:“ 如果您为指定的标识符注册了类并且必须创建新的单元格,则此方法通过调用其initWithFrame:方法来初始化该单元格。对于基于nib的单元格,此方法从提供的nib文件加载单元格对象。如果现有单元可用于重用,则此方法将调用单元的prepareForReuse方法。“

您的GalleryCell单元类是否有prepareForReuse方法?

您的单元类应该是UICollectionReusableView类的子类。检查一下。

答案 2 :(得分:1)

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

NSString *CellIdentifier = @"Gallery_Cell";

GalleryCell *cell;

if (cell==nil) {
    cell= (GalleryCell *)[self.flowCollection dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

    ImageItem *dets = [self.imageList objectAtIndex:indexPath.row];

    NSURL *mainImageURL = [NSURL URLWithString:dets.smallImageURL];

    [cell.image setImage:[UIImage new]];

    cell.image.contentMode = UIViewContentModeScaleAspectFill;
    cell.image.clipsToBounds = YES;                

    [cell.image setImageWithURL:mainImageURL placeholderImage:nil];

}

return cell;

}

答案 3 :(得分:1)

使用这种方法这个vl绝对可以100%工作。

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath;
{
   GalleryCell *cell1 = (GalleryCell*)[_resumeCollectionView cellForItemAtIndexPath:indexPath];
    cell1= nil;

}

答案 4 :(得分:0)

由于要重复使用单元格,因此必须在cellForIndexPath:中无条件地设置其内容。您的代码最终会设置图像,但它会使图像暂时保留为旧值 - 在重新使用之前设置的值。

快速解决方案(可能)是通过占位符图像提供setImageWithURL调用。我不知道SDImage库,但很好的猜测它会立即将imageView的图像设置为占位符图像(如果有的话)。

如果您没有或不想要占位符图片,可以在prepareForReuse子类中实现UICollectionViewCell并清除那里的imageView。

答案 5 :(得分:0)

我最终使用UICollectionView的“didEndDisplayingCell”方法并结束当前的Image下载并将图像设置为nil。这完美地工作,没有更多的“洗牌”或重复图像! :)