tableView
の画像を(Xcode 9とSwift 4)で非同期に読み込もうとしていますが、正しい方法があるようですが、tableView
をスクロールするとコードが機能しなくなります。だから基本的に私はにはゼロエラーが見つかりました。私はライン上の問題があるtableViewをスクロールするとnilが返されます
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTableViewCell
let feed = feeds[indexPath.row]
cell.titleLabel.text = feed.title
cell.pubDateLabel.text = feed.date
cell.thumbnailImageView.image = nil
if let image = cache.object(forKey: indexPath.row as AnyObject) as? UIImage {
cell.thumbnailImageView?.image = image
} else {
let imageStringURL = feed.imageUrl
guard let url = URL(string: imageStringURL) else { fatalError("there is no correct url") }
URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in
if let data = try? Data(contentsOf: url!) {
DispatchQueue.main.async(execute: {
guard let image = UIImage(data: data) else { fatalError("can't create image") }
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell // fast scroll issue line
updateCell.thumbnailImageView.image = image
self.cache.setObject(image, forKey: indexPath.row as AnyObject)
})
}
}).resume()
}
return cell
}
:
let updateCell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
私はスクロールダウンし、ゆっくりとすべてがうまく動作し、間違いが表示されない場合
は、ここに私のコードです。
私はどこで間違いをしたのですか?
なぜあなたはその行を削除しないで、updateCellをcellに変更し、ユーザーがロード中であることがわかるプレースホルダセルを返し、ダウンロード完了後にセルのイメージを変更する完了ハンドラを追加しますか? –
@ J.Doe私が理解しているように、セルが表示されているかどうかをチェックします。なぜなら、その行を使用しないと、表示するイメージが見つかるとイメージが常にどのように変化するかです。 –
私はあなたがCustomTablieViewCellのprepareForReuse関数を使うべきだと思います。イメージをゼロに戻します。 – cb89