Lukeksaunders
Lukeksaunders

Reputation: 25

How to stop tableview cells from glitching and flickering image when scrolling in swift?

I have a tableview that displays data from Firebase. It displays fine in the tableview but when scrolling begins, the table starts glitching or having the cells image and text reload and flicker which is very ugly. Help! Here's my code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell", for: indexPath) as! MainTableViewCell
func downloadPicture(finished: () -> Void) {
            cell.profilePicture.image = nil
                if let imageUrlString = self.payments[indexPath.row].picture,
                       let imageUrl = URL(string: imageUrlString) {
                        do {
                            let imageData = try Data(contentsOf: imageUrl)
                            cell.profilePicture.image = UIImage(data: imageData)
                            cell.profilePicture.layer.cornerRadius = cell.profilePicture.frame.size.width / 2
                            cell.profilePicture.clipsToBounds = true
                            cell.profilePicture.alpha = 1
                        }
                        catch {
                            print("Error fetching image - \(error)")
                    }
            }
            finished()
    }
    downloadPicture {
        print("success")
}
cell.amountLabel.text = "$\(self.payments[indexPath.row].amount ?? "")"
cell.detailsLabel.text = self.payments[indexPath.row].amount ?? ""
return cell

}

Upvotes: 0

Views: 1410

Answers (2)

Farrukh Makhmudov
Farrukh Makhmudov

Reputation: 482

@Lukeksaunders just go to GitHub Kinfisher. This library contains all functionality you want.

import Kingfisher
let url = URL(string: "https://example.com/image.png")
imageView.kf.setImage(with: url)

This library cache your images

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MainTableViewCell", for: indexPath) as! MainTableViewCell
    if let imageUrlString = self.payments[indexPath.row].picture,
       let imageUrl = URL(string: imageUrlString) {
        cell.profilePicture.kf.setImage(with: imageUrl)
    }
    cell.amountLabel.text = "$\(self.payments[indexPath.row].amount ?? "")"
    cell.detailsLabel.text = self.payments[indexPath.row].amount ?? ""
    return cell
}

Upvotes: 1

Virani Vivek
Virani Vivek

Reputation: 895

You can simply go with SDWebImage An asynchronous image downloader with cache management and efficient to use.

i.e. :

import SDWebImage

yourImageView.sd_setImage(with: URL(string: "yourImageURLFromFirebase.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

Upvotes: 2

Related Questions