I ran into a problem while scrolling from top to bottom of mine tableview. The reusable cell shows the old image until the new image is finished loading.
It should display the default placeholder for my image until a new image is uploaded, and after the upload is complete, change the imageView from the image placeholder to the currently loaded image. What should I do?
Refresh
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
}
}
}
}
source
share