【发布时间】:2017-03-16 18:33:02
【问题描述】:
好的,这里需要一点帮助。我是斯威夫特的新手。这是我的问题。
在为我的 UITableView 获取数据时,我是从 url 调用图像数据,因此在抓取重复使用的单元格时会有轻微的延迟,导致单元格显示旧数据半秒。我试图调用 func prepareForReuse 来重置属性,但它似乎不起作用。任何帮助表示赞赏!
这是我调用单元格时的代码:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.alpha = 0
let book = books[indexPath.row]
cell.textLabel?.text = book.bookTitle
cell.detailTextLabel?.text = book.postURL
let url = URL(string: book.postPicture)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
cell.alpha = 0
cell.backgroundView = UIImageView(image: UIImage(data: data!))
UIView.animate(withDuration: 0.5, animations: {
cell.alpha = 1
})
}
}
cell.contentView.backgroundColor = UIColor.clear
cell.textLabel?.backgroundColor = cell.contentView.backgroundColor;
cell.detailTextLabel?.backgroundColor = cell.contentView.backgroundColor;
func prepareForReuse(){
cell.alpha = 0
cell.backgroundView = UIImageView(image: UIImage(named: "book.jpg"))
}
return cell
}
【问题讨论】:
-
你不能这样覆盖
prepareForReuse。您必须继承UITableViewCell并在子类声明中覆盖它。您需要将dequeueReusableCell(withIdentifier:for:)的结果类型转换为您的子类。此外,从技术上讲,您应该首先将图像异步下载到磁盘,然后在用户滚动时将它们从磁盘加载到图像视图中。 -
好的,你有一个例子说明它是如何工作的吗?
标签: ios swift xcode uitableview