8

我有一个UICollectionView显示从 Internet 下载的图像网格的地方。我正在使用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;

}

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

4

6 回答 6

7

GalleryCell.m您需要添加prepareForReuse方法并在那里使_image变量无效(假设您image在单元格中有@property):

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

    _image = nil;
}
于 2014-03-03T22:41:17.627 回答
5

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

您的 GalleryCell 单元类有 prepareForReuse 方法吗?

你的单元类应该是 UICollectionReusableView 类的子类。并检查它。

于 2013-10-12T18:36:37.883 回答
1

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

于 2013-12-09T12:40:53.497 回答
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;

}
于 2014-08-20T05:15:02.287 回答
1

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

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

}
于 2014-12-16T20:28:41.933 回答
0

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

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

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

于 2013-10-12T18:37:27.543 回答