首页 > 解决方案 > 在 TableViewCell 中加载图像

问题描述

我想将图像从 url 加载到 productimage,但我的代码不起作用。
如何将图像加载到tableViewCells?

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier: "cellWomanSaved") as! WomanSavedTableViewCell

    let Data: DataModel

    Data = DataList[indexPath.row]

    cell.priceLabel.text = Data.Price
    cell.productLabel.text = Data.ImageURL
    cell.productImage.image = UIImage(data: url)

    if let url = URL(string: productLabel[indexPath.row]) {

        do {

            let data = try Data(contentsOf: url)
            self.swipeImage.image = UIImage(data: data)

        }catch let error {

            print(" Error : \(error.localizedDescription)")

        }
    }

    return cell
}

标签: swiftuitableview

解决方案


  • 在您的单元格中创建数据任务
  • 在 prepareForReuse 函数中取消数据任务
  • 将您的 url 传递给控制器​​ cellForRowAt 函数中的单元格
  • 所以用模型填充你的单元格并将值设置为属性

    class MyCell: UITableViewCell {
    
        // MARK: - Outlets
    
        @IBOutlet weak var priceLabel: UILabel!
        @IBOutlet weak var productLabel: UILabel!
        @IBOutlet weak var productImage: UIImageView!
    
    
        /// create dataTask for cancel in prepareForReuse function
        private var dataTask: URLSessionDataTask?
    
        /// Like this
        override public func prepareForReuse() {
           super.prepareForReuse()
            dataTask?.cancel()
        }
    
        func populate(with model: YourModel) {
            priceLabel.text = model.Price
            productLabel.text = model.ImageUrl
    
            /// You should set url in indexPath of your logo array([ImageUrl])
            let url = model.ImageUrl /// It's sample url for explain this is an url of your current index model
            if let imageUrl = url {
                downloaded(from: imageUrl)
            }
        }
    
        func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
            contentMode = mode
            dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
                guard
                    let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                    let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                    let data = data, error == nil,
                    let image = UIImage(data: data)
                    else { return }
                DispatchQueue.main.async() {
                    self.productImage.image = image
                }
            }
            dataTask?.resume()
        }
    }
    

在控制器的 tableView cellForRowAt 函数中:

let model: DataModel = DataList[indexPath.row]
cell.populate(with: model)

return cell

推荐阅读