cristan lika cristan lika - 8 months ago 42
iOS Question

Reusable cell old image showing

I am facing a problem when scrolling top to bottom then my

reusable cell showing old image until new image download completed.

It should show my default image placeholder until new image download when download finish then change the imageview from image placeholder to current download image. What should i do ?

Sorry for bad English. If you need any information let me know thanks


TableViewcontroller :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "ItemTableViewCell") as! ItemTableViewCell
let itemInfo = itemInfos[indexPath.row]

var image1 : UIImage?
var image2 : UIImage?

if let imgUrl1 = itemInfo.imageUrl {

image1 = ItemListViewController.imageCache.object(forKey: imgUrl1 as AnyObject) as? UIImage


if let imgUrl2 = itemInfo.cookerProfilePicUrl{
image2 = ItemListViewController.imageCache.object(forKey: imgUrl2 as AnyObject) as? UIImage

cell.configureCell(iteminfo: itemInfo, img1 : image1 ,img2 : image2)

return cell


func configureCell(iteminfo:ItemInfo , img1 : UIImage? , img2 : UIImage? ){

if img1 != nil {
imageViewItemPic.image = img1
imageViewItemPic.setImageFromURL(url: iteminfo.imageUrl!)

if img2 != nil {
imageViewCookerProfilePic.image = img2

imageViewCookerProfilePic.setImageFromURL(url: iteminfo.cookerProfilePicUrl!)

labelItemHeading.text = iteminfo.heading
labelItemDescription.text = iteminfo.description


update :

override func awakeFromNib() {
self.imageViewItemPic.image = UIImage(named: "resto-placeholder.png")


Update :

extension UIImageView {

func setImageFromURL(url: String) { {

let data = NSData.init(contentsOf: NSURL.init(string: url) as! URL)
DispatchQueue.main.async {

let image = UIImage.init(data: data as! Data)

ItemListViewController.imageCache.setObject(image!, forKey: url as AnyObject)

self.image = image


Answer Source

Since it is a reusable cell, it indeed "reuses" the cell with the old image. Then you need to update it every time the cell is shown in cellForRowAtIndexPath:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //then download image