Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable cell old image showing

I am facing a problem when scrolling from top to bottom of my tableview. The reusable cell shows old image until new image download is completed.

It should show my default image placeholder until new image is downloaded and when download is finished then change the imageView from image placeholder to current downloaded image. What should I do?

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


            }
        }
    }
}
like image 811
cristan lika Avatar asked Nov 20 '16 14:11

cristan lika


1 Answers

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
}
like image 147
Marie Dm Avatar answered Oct 06 '22 00:10

Marie Dm