简体   繁体   中英

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

}

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

ie :

import SDWebImage

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

@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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM