我有一個tableview,用來自firebase的數據填充它的單元格。每個單元格都擁有一個圖像,每個圖像都是異步加載並緩存的。 問題是隨機單元格將使用錯誤的圖像,雖然單元格中的其他數據是正確的。如果我滾動以便單元格離開視圖,則加載正確的圖像。UITableViewCell在重新使用後加載不正確的圖像
研究:
Images in UITableViewCells are loading wrong(真的不理解的OBJ C)
What is the correct way to use prepareForReuse?
圖像高速緩存:
import Foundation
import UIKit
let imageCache = NSCache<NSString, AnyObject>()
extension UIImageView {
func loadImageUsingCache(urlString: String) {
self.image = #imageLiteral(resourceName: "logo3")
if let cachedImage = imageCache.object(forKey: urlString as NSString) as? UIImage {
self.image = cachedImage
return
}
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async(execute: {
if let downloadedImage = UIImage(data: data!) {
imageCache.setObject(downloadedImage, forKey: urlString as NSString)
self.image = downloadedImage
}
})
}).resume()
}
}
泰伯維細胞
import Foundation
import Firebase
class GroupCell: UITableViewCell {
var group: Groups!
var members = [String]()
@IBOutlet weak var groupImage: UIImageView!
@IBOutlet weak var groupName: UILabel!
@IBOutlet weak var groupRep: UILabel!
@IBOutlet weak var memberCount: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func configureCell(group: Groups) {
self.group = group
self.groupName.text = group.name
self.groupRep.text = "\(group.groupScore)"
if let groupImage = group.groupImage {
self.groupImage.loadImageUsingCache(urlString: groupImage)
} else {
self.groupImage.image = //random image
}
for member in group.members {
self.members.append(member.key)
}
self.memberCount.text = "\(members.count)"
}
}
的TableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell") as? GroupCell {
let group = FriendSystem.system.activeGroups[indexPath.row]
cell.configureCell(group: group)
return cell
}
return UITableViewCell()
}
您可能想使用KingFisher之類的東西來讓您的生活更輕鬆。 https://github.com/onevcat/Kingfisher – DoesData
[異步圖像加載到UITableViewCell後滾動時,Swift圖像更改爲錯誤的圖像可能重複](https://stackoverflow.com/questions/35958826/swift-images-change錯誤的圖像,而滾動後異步圖像加載到) – DoesData
使用翠鳥和生活是好的。感謝您的建議 – Chris