简体   繁体   English

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

[英]How to load an image from URL and display it in tableView cell (Swift 3)

I have the image URL and I want to display that image in UIImageView which is placed in a tableView cell.我有图像 URL,我想在放置在 tableView 单元格中的 UIImageView 中显示该图像。 I created a custom cell and added an outlet for the imageView.我创建了一个自定义单元格并为 imageView 添加了一个出口。 Since I am loading news the URL changes accordingly.由于我正在加载新闻,因此 URL 会相应更改。 NOTE: I am using Alamofire to process my HTTP requests.注意:我正在使用 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"] ?? ""
    }
}

And loading info to my custom cell并将信息加载到我的自定义单元格

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!
 }

You can use this code to get image from url and can set a placeholder image as well.您可以使用此代码从 url 获取图像,也可以设置占位符图像。 for example:-例如:-

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()
    }}

This becomes quite easy, as you're using Alamofire.当您使用 Alamofire 时,这变得非常容易。 Unlike @Mochi's example, this won't block the interface.与@Mochi 的示例不同,这不会阻塞接口。

Here's an example:下面是一个例子:

Alamofire.request(news.imgUrl).response { response in
    if let data = response.data {
        let image = UIImage(data: data)
        cell?.thumbnailImage.image = image
    } else {
        print("Data is nil. I don't know what to do :(")
    }
}

*Please note I wasn't able to test this before I answered. *请注意,在我回答之前,我无法对此进行测试。 You may need to tweak this code a bit.您可能需要稍微调整此代码。

I used a Kingfisher library我使用了Kingfisher图书馆
Here are few easy steps to use the library. 以下是使用该库的几个简单步骤。


import Kingfisher

tableViewCell class: tableViewCell 类:

class MyCell: UITableViewCell {
    
    @IBOutlet weak var cellImg: UIImageView!
    
    @IBOutlet weak var cellLbl: UILabel!
    
}

Assign this class to your cell in storyboard

And finally, do this in CellForRowAt最后,在CellForRowAt执行此CellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell")! as! MyCell
        let url = URL(string: "https://files.pitchbook.com/website/files/jpg/food_delivery_800.jpg")
        cell.cellImg.kf.setImage(with: url)
        return cell
    }

That's it就是这样

Please Use SDWebImage .请使用SDWebImage It's an imageview category that downloads the image in the background without freezing your UI, and also provides caching as well.这是一个图像视图类别,可以在不冻结 UI 的情况下在后台下载图像,并且还提供缓存。 You can set a placeholder image as well.您也可以设置占位符图像。 Placeholders show until your actual image is downloaded.占位符会一直显示,直到您的实际图像下载完毕。 After downloading, the actual image in your cell's Imageview is updated automatically, and you don't need to use any completion handler.下载后,您单元格的 Imageview 中的实际图像会自动更新,您无需使用任何完成处理程序。

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.sd_setImageWithURL(NSURL(string: news.imgUrl), placeholderImage:UIImage(imageNamed:"placeholder.png"))
    return cell!
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM