簡體   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