简体   繁体   English

使用SDWebImage完成下载后,如何确定是否将图像分配给UIImageView?

[英]How to decide whether to assign image to UIImageView or not, once it finish downloading using SDWebImage?

SDWebImage is an extension to UIImageView . SDWebImageUIImageView的扩展。 There is a method: 有一种方法:

sd_setImageWithURL(NSURL(string: url), placeholderImage: placeholder, options: options, completed: { image, error, cache, url in 

    //do sth after it is completed
})

But in completed block I cannot decide whether to allow SDWebImage assign the image or not. 但是在completed块中,我无法决定是否允许SDWebImage分配图像。 It is assigned automaticaly without asking developer about permission to do this. 它是自动分配的,无需询问开发人员是否允许这样做。 The problem arise when I assign the image to UIImageView within UITableViewCell while scrolling the table. 当我在滚动表时将图像分配给UITableViewCell UIImageView时出现问题。

It is obvious that before it finishes downloading, that cell may be reused for different row, and finally there may be a different image. 显然,在完成下载之前,该单元可能会重用于不同的行,最后可能会有不同的映像。

How to fix it using this library? 如何使用此库修复它?

In following question: Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling , there is an answer that SDWebImage solve this problem, but it is not true, or I missed sth. 在以下问题中: 从UITableView单元内的URL加载异步图像-滚动时图像变为错误图像 ,有一个答案是SDWebImage解决了此问题,但这不是真的,或者我错过了。

This shouldn't be necessary. 这不是必须的。 If you look inside the implementation of the UIImageView category you will see this: 如果查看UIImageView类别的实现,您将看到以下内容:

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
    [self sd_cancelCurrentImageLoad];
    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

What this shows you is that the minute you call setImage it cancels the download associated with the image view instance. 这说明您在调用setImage的那一刻取消了与图像视图实例关联的下载。 Since UITableView reuses its views this should not be an issue. 由于UITableView重用了其视图,因此这应该不是问题。 See how they associate the imageView and URL together. 了解他们如何将imageView和URL关联在一起。

Your issue is probably the fact that you are not resetting your imageView's image property to nil everytime. 您的问题可能是您没有将imageView的image属性每次都重置为nil。 So inside cellForRow you probably want: 因此,在cellForRow内部,您可能想要:

cell.imageView.image = nil
cell.imageView.sd_setImageWithURL(...)

When you start a new load the image view cancels any current load. 当您开始新的加载时,图像视图会取消任何当前加载。 So, if the image view is reused this problem is avoided. 因此,如果重新使用图像视图,则可以避免此问题。

If you don't have a new image to set for some reason then you can call sd_cancelCurrentImageLoad and explicitly set your placeholder image. 如果由于某种原因没有设置新图像,则可以调用sd_cancelCurrentImageLoad并显式设置占位符图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM