集合视图单元格中的图像不正确

时间:2016-06-21 14:20:31

标签: ios objective-c uicollectionview sdwebimage

我使用sdwebimage来缓存图像。 现在imagesArr是我想首先显示所有单元格的图像数组。 我在后台下载图像然后保存到磁盘中,所以当我希望这些图像处于离线模式时,我可以从磁盘中获取。

但在某些情况下,当我滚动collectionView时,图像设置不正确,然后再次滚动图像看起来是正确的。

这是我在cellForItemAtIndexPath中实现的以下代码。我试图调试,但似乎数据正确,图像名称也正确。

此外,collectionView在滚动方面也很滞后。请帮我找到问题。

 if(imagesArr.count>0)
{
    ClothesImage *obj_image=[imagesArr objectAtIndex:0];
    NSString *fileName = [stringPath stringByAppendingFormat:@"/%@",obj_image.imagePath];
    NSLog(@"FILES NAMES %@ ", obj_image.imagePath);
    NSData *data = [NSData dataWithContentsOfFile:fileName];
    if(data!=nil){
        UIImage *image=[UIImage imageWithData:data];
        cell.imgProduct.image=image;
    }
    else{
        NSString *offline=[user_defaults objectForKey:@"offline"];

        if([offline integerValue]==0){
            cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"];
            NSString *str_url=[NSString stringWithFormat:@"%@/%@",WEB_THUMB_IMAGE,obj_image.imagePath];
            str_url = [NSString stringWithFormat: @"%@",[str_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

            [cell.imgProduct setImageWithURL:[NSURL URLWithString:str_url] placeholderImage:[UIImage imageNamed:@"noImageThumb"] options: SDWebImageRefreshCached];

            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            [manager downloadWithURL:[NSURL URLWithString:str_url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
                NSString *stringPathImage = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"WebThumb"];
                NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
                NSString *fileName = [stringPathImage stringByAppendingFormat:@"/%@",obj_image.imagePath];
                [data writeToFile:fileName atomically:YES];
                NSLog(@"DOWNLOADED IMAGE %@",fileName);

   }];
        }
        else
        {
            cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"];
        }
    }
} else{
    cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"];
}

1 个答案:

答案 0 :(得分:1)

我认为有几种方法可以改善这一点。

看起来你正在重复SDWebImage为你做的很多工作。该库将缓存图像并按需获取它们。您应该考虑让该库将您的文件预取到缓存中,而不是自己尝试预取并将它们写入磁盘。最终在-cellForRowAtIndexPath时,您只需要两种情况:一种用于在设备离线时设置图像,另一种用于从缓存中获取或设置图像,SDWebImage为您提供:

    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                  placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

就是这样。你所做的所有缓存和切换都没有必要。另一件需要确定的是你的细胞子类方法-prepareForReuse,你正在填写图像。

相关问题