如何从 URL 加载图像并将其显示在 tableView 单元格中 (Swift 3)

Adi*_*ina 1 ios swift alamofire

我有图像 URL,我想在放置在 tableView 单元格中的 UIImageView 中显示该图像。我创建了一个自定义单元格并为 imageView 添加了一个出口。由于我正在加载新闻,因此 URL 会相应更改。注意:我正在使用 Alamofire 来处理我的 HTTP 请求。

struct News {
    let title: String
    let text: String
    let link: String
    let imgUrl: String

    init(dictionary: [String:String]) {
        self.title = dictionary["title"] ?? ""
        self.text = dictionary["text"] ?? ""
        self.link = dictionary["link"] ?? ""
        self.imgUrl = dictionary["imgUrl"] ?? ""
    }
}
Run Code Online (Sandbox Code Playgroud)

并将信息加载到我的自定义单元格

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? newsCellTableViewCell
    let news = newsData[indexPath.row]
    cell?.headline.text = news.title
    cell?.excerpt.text = news.text
    cell?.thumbnailImage.text = news.imgUrl
    return cell!
 }
Run Code Online (Sandbox Code Playgroud)

San*_*ill 5

您可以使用此代码从 url 获取图像,也可以设置占位符图像。例如:-

cell.imageView?.imageFromURL(urlString:  "urlString", PlaceHolderImage: UIImage.init(named: "imagename")!)

extension UIImageView {

 public func imageFromServerURL(urlString: String, PlaceHolderImage:UIImage) {

        if self.image == nil{
              self.image = PlaceHolderImage
        }

        URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in

            if error != nil {
                print(error ?? "No Error")
                return
            }
            DispatchQueue.main.async(execute: { () -> Void in
                let image = UIImage(data: data!)
                self.image = image
            })

        }).resume()
    }}
Run Code Online (Sandbox Code Playgroud)