cristan lika cristan lika - 19 days ago 11
iOS Question

Reusable cell old image showing

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

tableview
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

Update

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
}


Xib:

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

if img1 != nil {
imageViewItemPic.image = img1
}
else{
print("hi1")
imageViewItemPic.setImageFromURL(url: iteminfo.imageUrl!)
}


if img2 != nil {
imageViewCookerProfilePic.image = img2

}
else{
imageViewCookerProfilePic.setImageFromURL(url: iteminfo.cookerProfilePicUrl!)
}

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


}


update :

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

}


Update :

extension UIImageView {

func setImageFromURL(url: String) {

DispatchQueue.global().async {

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

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 {
        cell.image=placeholder_image
        //then download image
}