首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可重用单元格未调用prepareForReuse函数

可重用单元格未调用prepareForReuse函数
EN

Stack Overflow用户
提问于 2017-03-17 02:33:03
回答 1查看 7.7K关注 0票数 4

好了,这里需要一点帮助。我是Swift的新手。这是我的问题。

当为我的UITableView获取数据时,我从url调用图像数据,所以在抓取重用的单元格时会有轻微的延迟,导致单元格显示旧数据的时间为半秒。我尝试调用func prepareForReuse来重置属性,但似乎不起作用。如有任何帮助,我们不胜感激!

下面是我调用cell时的代码:

代码语言:javascript
复制
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


}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-17 02:58:29

你应该在你的自定义类覆盖中继承UITableView单元格:

代码语言:javascript
复制
import UIKit

class CustomTableViewCell: UITableViewCell {

    override func prepareForReuse() {
        // your cleanup code
    }
}

然后在UITableViewDataSource方法中重用自定义单元格:

代码语言:javascript
复制
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: CustomTableViewCell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomTableViewCell
    return cell
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42842207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档