UICollectionView中的图片懒加载问题

3

我刚接触iOS应用开发。我正在为UICollectionView实现图片懒加载。图片能够显示,但当我滚动UICollectionView后,图片会改变位置,并且有些图片会重复出现,所有的图片都应该是唯一的。这是我的代码:

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

    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];

    cell.imageview_collectnvw.layer.cornerRadius=6.0f;
    cell.imageview_collectnvw.layer.masksToBounds=YES;

    dispatch_queue_t queue = dispatch_queue_create("patientlist",NULL);
    dispatch_async(queue, ^{


        NSString *str=[[[search_array objectAtIndex:indexPath.row]valueForKey:@"friend"]valueForKey:@"linkedin_photo"];

        NSLog(@"cell index path --- is %d",indexPath.row);

        NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
        dispatch_sync(dispatch_get_main_queue(), ^{

            if ([[collectionView indexPathsForVisibleItems] containsObject:indexPath]) {

                MyCell *cell = (MyCell*)[collectionView cellForItemAtIndexPath:indexPath];

                cell.imageview_collectnvw.image=[UIImage imageWithData:data];

            }

            [cell setNeedsLayout];

            NSLog(@"cell index path main is %d",indexPath.row);

        });
    });


    return cell;
}

这可能是一个愚蠢的问题,但我需要答案...如果有人能回答这个问题,那将是非常有帮助的。提前致谢。
4个回答

5

当使用UICollectionView时,应该使用indexPath.item而不是indexPath.row


当我需要同时使用section和row时怎么办? - Sazzad Hissain Khan
你仍然可以访问indexPathsection属性。 - konrad.bajtyngier
我应该使用“section”和“item”代替“section”和“row”吗? - Sazzad Hissain Khan

3
在一个UICollectionViewUITableView中,单元格是可重用的。这就是你调用dequeueReusableCellWithReuseIdentifier所得到的结果。因此,你会得到一个旧的单元格,该单元格最初分配了图像,如果在异步调用之前没有显式地将其设置为nil,则它仍将具有旧图像,直到新图像被下载并设置。因此,修复方法是在下载成功之前将cell.imageview_collectnvw.image分配为nil或占位图像。同时,在内存中管理一个UIImages数组,并根据需要从内存中删除,以获得更好的性能。可以查看SDWebImage,它可以将图片缓存到内存和磁盘中,并且据我所见性能非常出色。了解如何设置表格或UICollectionView中的图像加载的良好起点是查看苹果提供的懒加载示例。

0

你必须使用多个部分和行。但是,你只使用indexPath.row加载图像,这可能会在不同的部分中重复。因此,你的部分图像应该是重复的。请确保你的键同时使用部分和项目生成。

对于Swift

func getCachedIndexKey(index:NSIndexPath) -> String {
    return "section:\(index.section)item:\(index.item)"
}

这个方法将返回一个唯一的键(虽然是字符串)。请理解情况并准备您自己的唯一索引键(整数)。


0
你可以使用SDWebImage来进行图片的懒加载。它会异步地加载图片并将其缓存,无需一遍又一遍地加载。

在SDWebImage中,它显示ld: 找不到SDWebImage-3.3框架,clang: 错误:链接器命令失败,退出码为1(使用-v查看调用),但我已经导入了错误并在其他链接器中添加了-ObjC。 - Namrata Sen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接