UITableViewCell在重新使用后加载不正确的图像
问题描述:
我有一个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()
}
答
听起来像是你需要将prepareForReuse
方法添加到您的GroupCell类。
在该方法中,添加self.groupImage.image = nil
它将重置您的图像视图为空,直到设置正确的图像。
+0
我之前实际上已经实施了此代码,但没有成功。这是我提到的其中一条线索 – Chris
您可能想使用KingFisher之类的东西来让您的生活更轻松。 https://github.com/onevcat/Kingfisher – DoesData
[异步图像加载到UITableViewCell后滚动时,Swift图像更改为错误的图像可能重复](https://stackoverflow.com/questions/35958826/swift-images-change错误的图像,而滚动后异步图像加载到) – DoesData
使用翠鸟和生活是好的。感谢您的建议 – Chris