我有一个tableview显示来自Firebase的数据。它在tableview中显示得很好,但当滚动开始时,表格开始出现故障或让单元格图像和文本重新加载和闪烁,这很难看。的帮助!下面是我的代码:
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
}
您可以简单地使用SDWebImage一个异步图像下载器,具有缓存管理和高效使用。
。:
import SDWebImage
yourImageView.sd_setImage(with: URL(string: "yourImageURLFromFirebase.jpg"), placeholderImage: UIImage(named: "placeholder.png"))
@Lukeksaunders只是去GitHub kininfisher。这个库包含了你需要的所有功能
import Kingfisher
let url = URL(string: "https://example.com/image.png")
imageView.kf.setImage(with: url)
这个库缓存你的图像
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
}