在我的iOS应用程序中,我已经创建了表格和其他许多东西,但现在,在实施一个"评论"标签和" reviewCell"中的图像在向下滚动并再次向上滚动后消失,我无法弄清楚原因! 我已经调试了代码但是一切都设置正确。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reviewCell", for: indexPath) as! ReviewCell
let review = self.reviews[indexPath.row]
if review.authorName == nil{
self.reviews[indexPath.row].authorName = NSLocalizedString("ANONYMOUS", comment: "")
cell.authorLabel.text = NSLocalizedString("ANONYMOUS", comment: "")
}
else{
cell.authorLabel.text = review.authorName
}
cell.ratingView.rating = Double(review.rating)
cell.reviewTextLabel.text = review.text
if(self.reviewProfileImages[indexPath.row] == nil){
cell.profileImage.image = UIImage()
downloadImageAndSaveForKey(key: indexPath.row, url: review.profile_photo_url);
}
else{
cell.profileImage.image = self.reviewProfileImages[indexPath.row]!;
}
return cell
}
ReviewCell:
class ReviewCell: UITableViewCell {
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var ratingView: CosmosView!
@IBOutlet weak var reviewTextLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
图像保存在Map [Int:UIImage]中,以防止每次都下载图像。
不滚动(在模拟器上,图像和作者标签加载仅显示几毫秒):
故事板:
DownloadImageAndSaveForKey函数
func downloadImageAndSaveForKey(key: Int, url: String){
let catPictureURL = URL(string: url)!
let session = URLSession(configuration: .default)
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
if (response as? HTTPURLResponse) != nil {
if let imageData = data {
self.reviewProfileImages[key] = UIImage(data: imageData)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
}
打印第0行(所有内容都正确显示):Row 0, authorLabelText: Optional("Anonymous"), profile image Optional(<UIImage: 0x1d40bc380>, {128, 128})
打印第0行(滚动后,消失):Row 0, authorLabelText: Optional("Anonymous"), profile image Optional(<UIImage: 0x1d40bc380>, {128, 128})