swift - 在 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
}
解决方案
- 在您的单元格中创建数据任务
- 在 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
推荐阅读
- javascript - 无法在父组件中运行子组件方法
- python-3.x - 皮威。如何选择所有带有预取字段的外键字段的模型项?
- asp.net-core - FHIR 的通用数据类型对象从 .NET Core 中的 JSON 解析
- ios - 如何更改标签栏控制器的选定索引?
- c# - 为什么我的查询(包含作为命令文本的 sql 文件)超时?
- .net - 从 NATS 切换到 RabbitMQ
- javascript - 角度图像上传不适用于 Internet Explorer,但它适用于谷歌浏览器
- awesome-wm - awesome-wm:为切换视图桌面创建快捷键
- javascript - window.history 删除除当前 url 之外的历史堆栈
- apache-flink - 是否可以在 Flink 的 Job Manager 上注册指标?