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

问题描述 投票:0回答:4

我有图像 URL,我想在 UIImageView 中显示该图像,该图像放置在 tableView 单元格中。 我创建了一个自定义单元并为 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!
 }
ios swift alamofire
4个回答
8
投票

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

cell.imageView?.imageFromServerURL(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()
    }}

1
投票

这变得非常简单,因为您正在使用 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 :(")
    }
}

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


1
投票

我使用了

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

中执行此操作
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
    }

就是这样


0
投票

请使用SDWebImage。它是一个 imageview 类别,可以在后台下载图像而不会冻结您的 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!
}
© www.soinside.com 2019 - 2024. All rights reserved.