需求要求列表页使用圆角头像,则使用了SDWebImageDownloader
将图片下载下来,经过裁剪后再赋值,如果滑动较快,会导致 cell 上的头像一开始显示的是其他用户的,如果滑动特别快,会切换很多次最终才会显示出来。如下是错误代码:
self.avatarImageView.image = UIImage.init(imageLiteral: "avatarImage")
self.cellCurrentAvatarImageURL = entity.avatarUrl!
//头像
weak var weakSelf = self
SDWebImageDownloader.sharedDownloader().downloadImageWithURL(entity.avatarUrl!, options: SDWebImageDownloaderOptions.UseNSURLCache, progress: { (receivedSize :NSInteger, expectedSize :NSInteger) in
}) { (image :UIImage!, data :NSData!, error :NSError!, finished :Bool!) in
if finished == true && image != nil{
dispatch_async(dispatch_get_main_queue(), {
//这里判断也是错误的想法,因为调用 set 方法的时候,已经将cellCurrentAvatarImageURL的值改变了
if weakSelf?.cellCurrentAvatarImageURL == weakSelf?.entity.avatarUrl {
weakSelf?.avatarImageView.image = image.cornerRadius((weakSelf?.avatarImageView.bounds)! ,radius: 17.5)
} else {
print("weakSelf?.cellCurrentAvatarImageURL: \(weakSelf?.cellCurrentAvatarImageURL)")
print("weakSelf?.entity.avatarUrl: \(weakSelf?.entity.avatarUrl)")
}
})
}
}
其实使用 sd_setImageWithURL
即可解决问题,在下载完成图片后,绘制成圆角然后赋值。使用 sd_setImageWithURL
为什么不会出问题?是因为 SDWebImage 框架已经考虑到了这个问题,内部做了处理,当一个 UIImageView 的对象重复请求下载赋值不同的图片时,会将之前的请求都停止掉,下载最新的图片。不会导致出问题的代码如下:
self.avatarImageView.sd_setImageWithURL(entity.avatarUrl!, placeholderImage: UIImage.init(imageLiteral: "avatarImage"), options: SDWebImageOptions.CacheMemoryOnly) { (image, error, cacheType, imageURL) in
if error == nil && image != nil{
weakSelf?.avatarImageView.image = image.cornerRadius((weakSelf?.avatarImageView.bounds)! ,radius: 17.5)
}
}
网友评论