使用UIImageView + AFNetworking,直到滚动才会显示图像

时间:2016-11-23 22:50:10

标签: ios swift uitableview afnetworking

我正在使用UIImageView+AFNetworking在表格单元格中加载图片,但是 从服务器下载的图像不会显示在单元格中,直到再向下滚动。我认为我需要在tableView中重新加载数据,但我不知道在哪里放置重新加载代码。

以下是代码:

@IBOutlet weak var refresherTool: UIRefreshControl!



override func viewDidLoad() {
    super.viewDidLoad()


    let _ = dataRefresher.sharedInstance.refreshVideos(fromUrl: "https://api.vid.me/videos/featured", withLimit: "100", withOffset: "0", completion: {
        featuredVideos in dataRefresher.sharedInstance.featuretVideos = featuredVideos
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    })

}

@IBAction func refreshBtn(_ sender: UIRefreshControl) {
    let _ = dataRefresher.sharedInstance.refreshVideos(fromUrl: "https://api.vid.me/videos/featured", withLimit: "100", withOffset: "0", completion: {
        featuredVideos in dataRefresher.sharedInstance.featuretVideos = featuredVideos
        self.refresherTool.endRefreshing()
        DispatchQueue.main.async{
            self.tableView.reloadData()
        }
    })
    refresherTool.endRefreshing()
}


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if dataRefresher.sharedInstance.featuretVideos == nil {
        return 0
    }
    return 100
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "featuredCell", for: indexPath)
    //  if dataRefresher.sharedInstance.featuretVideos == nil { return cell}
    let newImage = UIImageView()
    newImage.setImageWithUrl(URL.init(string: dataRefresher.sharedInstance.getVideosThumbnailUrls(fromVideos: dataRefresher.sharedInstance.featuretVideos)[indexPath.row])!, placeHolderImage: #imageLiteral(resourceName: "first"))
   // newImage.setImageWithUrl(URL.init(string: urls[indexPath.row])!)
    cell.imageView?.image = newImage.image

    cell.textLabel?.text = dataRefresher.sharedInstance.getVideosTitels(fromVideos: dataRefresher.sharedInstance.featuretVideos)[indexPath.row]

    print(indexPath.row)
    print(newImage.image!)
    return cell
}

1 个答案:

答案 0 :(得分:1)

setImageWithUrl方法是异步,这意味着如果引用的图像尚未在本地缓存中,则只会在将来某个时间下载。

但是,您的代码会尝试立即取出图像:

let newImage = UIImageView()
newImage.setImageWithUrl(..., placeHolderImage: ...)
cell.imageView?.image = newImage.image <-- synch call, image is nil here at first!

幸运的是,没有必要重新加载表格视图或做任何其他神秘的技巧;只是停止做不必要的事情。

删除临时UIImageView并将图像直接加载到单元格的UIImageView中。

以上代码变为:

cell.imageView?.setImageWithUrl(..., placeHolderImage: ...)