【发布时间】:2018-09-20 00:39:16
【问题描述】:
我在 tableview 中有一个从 Json 下载的图像,一切正常,但是在看到相应图像之前滚动时,它会加载另一个图像几秒钟(这些图像是表格中已经可见的图像)。
我的数据结构是:
struct Data: Decodable {
let name: String
let img: String
let phone: String
let linktaller: String
let web: String
}
我加载图片的单元格的代码是:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? AseguradorasTableViewCell else { return UITableViewCell() }
cell.titleLbl.text = company[indexPath.row].name
.
.
.
// load image
if let imageURL = URL(string: company[indexPath.row].img) {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
cell.myImage.image = image
}
}
}
}
return cell
}
加载数据的函数是:
func downloadJSON() {
let url = URL(string: "http://myserver.com/data.json")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
do {
self.company = try JSONDecoder().decode([Data].self, from: data!)
print(self.company)
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
} catch let jsonError{
print("error + \(jsonError)")
}
}
}.resume()
}
查看图片了解更多详情:
欢迎任何建议来解决这个问题。
【问题讨论】:
标签: ios swift uitableview tableview