需求要求列表頁使用圓角頭像,則使用了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)
}
}