繁体   English   中英

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

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

我有图像 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"] ?? ""
    }
}

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

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

您可以使用此代码从 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()
    }}

当您使用 Alamofire 时,这变得非常容易。 与@Mochi 的示例不同,这不会阻塞接口。

下面是一个例子:

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

*请注意,在我回答之前,我无法对此进行测试。 您可能需要稍微调整此代码。

我使用了Kingfisher图书馆
以下是使用该库的几个简单步骤。


import Kingfisher

tableViewCell 类:

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

Assign this class to your cell in storyboard

最后,在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
    }

就是这样

请使用SDWebImage 这是一个图像视图类别,可以在不冻结 UI 的情况下在后台下载图像,并且还提供缓存。 您也可以设置占位符图像。 占位符会一直显示,直到您的实际图像下载完毕。 下载后,您单元格的 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