我有一个应用程序从API下载JSON数据并将其设置在tableview单元格中。在随机向上/向下滚动细胞图像的某个时候,在它有一个正确的图像之前,它可能会自行改变几次。没有任何问题的文本数据。起初我认为问题是细胞的可重用性,所以我需要在实际设置新图像之前销毁数据。所以我加了TableViewCell的这种方法cellForRowAt路径设置单元格之前销毁数据:可重复使用的单元格或错误的异步图像从TableView中的JSON数据下载
func destroyCellData() {
self.newsImageView.image = nil
self.newsTitleLabel.text = nil
self.tagLabel.text = nil
}
那么实际的方法设置单元格:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "newscell") as? NewsTableViewCell else {
print("No such cell")
exit(14)
}
cell.loadingImageIndicator.startAnimating()
let data = dataManager.getData()
let dataToInsert = data[indexPath.row]
cell.destroyCellData()
cell.setDataToCell(with: dataToInsert)
return cell
}
和方法setDataToCell是:
func setDataToCell(newsObject: jsonNews) {
self.newsTitleLabel.text = newsObject.title
self.tagLabel.text = newsObject.tag
let url = newsObject.imageURL
self.newsImageView.loadImageUsingCacheWithURLString(url, placeholder: UIImage(named: "ViewPlaceholder"), indicator: loadingImageIndicator)
}
最后我加载单元格内的异步图像:
let imageCache = NSCache<NSString, UIImage>()
extension UIImageView {
func loadImageUsingCacheWithURLString(_ URLString: String, placeholder: UIImage?, indicator: UIActivityIndicatorView? = nil) {
self.image = nil
if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
self.image = cachedImage
indicator?.stopAnimating()
return
}
guard let encodedString = URLString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
print("Error Loading URL")
return
}
if let url = URL(string: encodedString) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
OperationManager.UI {
self.image = placeholder
indicator?.stopAnimating()
}
return
}
if let data = data {
if let downloadedImage = UIImage(data: data) {
print(URLString)
imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
OperationManager.UI {
self.image = downloadedImage
indicator?.stopAnimating()
}
}
}
}).resume()
}
}
}
所以我有问题是 - 问题出在哪里我下载和设置图像的方法或是单元格的可重用性的问题?如果可能的话,给我一个更适合将图像设置为单元格的方式。在此先感谢
正确的图像被替换为不正确的图像? – ColdLogic
@ColdLogic是的,但它偶尔出现,最终在滚动tableview时被替换为正确 –
查看此链接中的扩展名:https://github.com/antonio081014/TwitterPractice/blob/master/TwitterPractice/Helper/Extensions .swift 用存储正确url字符串的字符串变量创建子类,然后当收到图像数据时,检查是否收到正确的图像。 –