我面临一个非常奇怪的问题。我的UICollectionView为多个单元格渲染相同的图像。我正在从外部源加载图像。这是我的代码。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: TTElementViewCell? = collectionView.dequeueReusableCell(withReuseIdentifier:reuseIdentifier, for: indexPath) as? TTElementViewCell
cell?.imageView.image = UIImage(named:"dummyImage.png")
let uniqueImageName = TTApplicationModel.sharedModel.cacheKey(fbUrl: crItem.profileImageUrl)
DispatchQueue.main.async {
cell?.load(cacheKey: uniqueImageName, url: crItem.profileImageUrl)
}
return cell!
}
这是我在名为TTElementViewcell
的自定义单元格类中的加载函数,它扩展了UICollectionViewCell
。
func load(cacheKey:String,url:String){
let loader = TTAsyncImageLoader()
let uniqueImageName = TTApplicationModel.sharedModel.cacheKey(fbUrl: url)
if uniqueImageName != ""{
loader.load(cacheKey: uniqueImageName, url: URL(string:url)!, completion: { (image:UIImage?) in
DispatchQueue.main.async {
self.imageView.image = image!
}
})
}
}
以下是TTAsyncImageLoader
类的详细信息。
import UIKit
class TTAsyncImageLoader {
fileprivate let model = TTApplicationModel.sharedModel.imageCache
private func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
func load(cacheKey:String, url:URL,completion:@escaping (_ success:UIImage?)->Void) {
if let image = self.model.object(forKey: cacheKey as AnyObject) as? UIImage{
completion(image)
return
}
self.getDataFromUrl(url: url) { (imgData:Data?, response:URLResponse?, error:Error?) in
if error == nil{
self.model.setObject(UIImage(data: imgData!)!, forKey: cacheKey as AnyObject)
completion(UIImage(data: imgData!)!)
}else{
print("TTAsyncImageLoader::load \(error!.localizedDescription) ")
}
}
}
}
输出显示在图像中: