下载每个图像后重新加载 tableview

Reload tableview after each image is downloaded

我做了以下代码并且工作得相当不错,但是我找不到在下载每张图像后重新加载 tableView 的方法。我正在使用 Alamofire 下载所有内容列表数据和图像。

如何从扩展访问 tableView?

如果有人能给我任何建议,我将不胜感激:)

import UIKit
import Alamofire
import AlamofireImage

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var jsonArray: NSArray?
    var nameArray: Array<String> = []
    var imageURLArray: Array<String> = []

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

    func downloadDataFromAPI(){
        Alamofire.request("http://private-135b4e-solamente.apiary-mock.com/pokemonList") .responseJSON { response in
            if let JSON = response.result.value{
                self.jsonArray = JSON as? NSArray
                for item in self.jsonArray! as! [NSDictionary]{
                    //5.
                    let name = item["name"] as? String
                    let imageURL = item["image"] as? String
                    self.nameArray.append((name)!)
                    self.imageURLArray.append((imageURL)!)
                }
                print(self.nameArray)
                self.tableView.reloadData()
            }
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.nameArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "mycell")
        cell.textLabel?.text  = nameArray[indexPath.row]
        cell.imageView!.downloaded(from: imageURLArray[indexPath.row])

        return cell
    }

}

extension UIImageView {
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {  // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() {
                self.image = image
            }
            }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

您无需在下载每个图像后重新加载 table 视图。您需要 return 此函数回调中的图像 func downloaded 您可以在 objective-c.

中找到类似的答案

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling