如何使用Nuke预热器在TableView单元中进行图像缓存:iOS

时间:2019-05-15 11:00:00

标签: ios swift uitableview uiimageview

我的UITabelView加载缓慢,滚动也缓慢。我在Url中用nuke从UITableViewCell取了图像

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = carTableView.dequeueReusableCell(withIdentifier: "CarDetailsTableViewCell") as! CarDetailsTableViewCell
    if let model = Obj![indexPath.row].model{
         cell.nameLabel.text = model
    }

    if let url = Obj![indexPath.row].image{
         let imageURL = URL(string: url)
         Nuke.loadImage(with: imageURL!, into: cell.carImage)

    }
    return cell
}

2 个答案:

答案 0 :(得分:0)

使用Nuke加载图像非常简单,您可以按照以下代码段进行操作,

    import Nuke

    Nuke.loadImage(with: URL(string: "http://yourImageUrl.jpeg"), into: cell.profileImage)

答案 1 :(得分:0)

为防止加载/滚动缓慢,请使用占位符图像。下面的示例代码显示了如何预热图像。

class YourViewController: UIViewController {
  var preheater = ImagePreheater(pipeline: ImagePipeline.shared)
  var requests: [ImageRequest]?
  // You need to populate remoteImages with the URLs you want prefetched
  var remoteImages = [URL]()

  override func viewDidLoad() {
    super.viewDidLoad()
    fetchImages()
  }

  func fetchImages() {
    requests = remoteImages.map {
      var request = ImageRequest(url: $0)
      request.priority = .high
      return request
    }
    if let requests = requests, requests.count > 0 {
      preheater.startPreheating(with: requests)
    }
  }

  deinit {
    if let requests = requests, requests.count > 0 {
      preheater.stopPreheating(with: requests)
    }
  }

  // This is your code modified to use placeholder

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = carTableView.dequeueReusableCell(withIdentifier: "CarDetailsTableViewCell") as! CarDetailsTableViewCell
    if let model = Obj![indexPath.row].model{
     cell.nameLabel.text = model
    }

    if let url = Obj![indexPath.row].image{
      let imageURL = URL(string: url)
      Nuke.loadImage(with: imageURL!, options: ImageLoadingOptions(
        placeholder: UIImage(named: "your-placeholder-image"),
        transition: .fadeIn(duration: 0.20)
      ), into: cell.carImage)
    }

    return cell
  }

}