我想将图像从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
}
答案 0 :(得分:0)
更改此行
if let url = URL(string: productLabel[indexPath.row]) {
收件人
if let url = URL(string: productLabel[indexPath.row].addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)) {
答案 1 :(得分:0)
您可以使用 SDWebImage 库轻松地从URL加载图像并将其显示在imageView中。 SDWebImage非常方便,因为它可以下载并缓存图像,下次当您希望从相同的URL获取图像时,它将从缓存中加载图像。
它真的很容易使用。您可以通过cocoapod,carthage或将库代码手动添加到项目中。
这是github存储库的链接:
答案 2 :(得分:0)
因此,用模型填充单元格并将值设置为属性
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