重用单元格效果不佳 - TableView [英] Reusing cell doesn't work well - TableView

查看:25
本文介绍了重用单元格效果不佳 - TableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的手机按钮有问题.在我的 tableView 中,每一行都由:一个图像、一些标签和一个按钮组成.该按钮有一个复选标记图像.单击它时,按钮的图像会发生变化.问题是另一个按钮的图像也会无缘无故地改变.发生这个错误是因为我的细胞被重复使用了.

I have a problem about my cell's button. In my tableView each row is composed by: an image, some labels and a button. The button has a checkmark image. When it is clicked, the button's image changes. The problem is that also another button's image changes without reason. This mistake happens because my cell is reused.

我尝试在 TableViewCell 中使用 prepareForReuse 方法,但没有任何反应.我也尝试过 selectedRowAt 但我没有任何结果.请帮帮我.

I have tried to use prepareForReuse method in TableViewCell but nothing happens. I've also tried with selectedRowAt but I didn't have any results. Please help me.

图片 1:

图片 2:

这是我的自定义单元格中的函数:

  override func prepareForReuse() {
    if checkStr == "uncheck"{
        self.checkBook.setImage(uncheck, for: .normal)
    } else if checkStr == "check"{
        self.checkBook.setImage(check, for: .normal)
    }
}

func isPressed(){
    let uncheck = UIImage(named:"uncheck")
    let check = UIImage(named: "check")
    if self.checkBook.currentImage == uncheck{
        checkStr == "check"
    } else self.checkBook.currentImage == check{
        checkStr == "uncheck"
    }
}

在我的 tableView 中:

  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedCell: ListPropertyUserCell = tableView.cellForRow(at: indexPath) as! ListPropertyUserCell
    let uncheck = UIImage(named:"uncheck")
    let check = UIImage(named: "check")
    if selectedCell.checkBook.imageView?.image == uncheck{
        selectedCell.checkStr = "check"
    } else if selectedCell.checkBook.imageView?.image == check{
        selectedCell.checkStr = "uncheck"
    }
}

推荐答案

从您帖子中的信息来看,这看起来像是一个单元格重用问题.问题在于 tableView 重用单元格而不是创建新单元格,以保持性能.如果您尚未重置单元格的状态,则重用的单元格将保持在旧状态的配置.

From the information in your post, this looks like a cell reuse issue. The problem is that the tableView reuses the cells rather than creating new ones, to maintain performance. If you haven't reset the cell's state, the reused cell will be remain configured in the old state.

为了快速修复,您可以在 UITableViewCell 上实现 prepareForReuse 方法.

For a quick fix, you can implement the prepareForReuse method on UITableViewCell.

但是,如果您希望在滚动 tableView 后选中复选框,则需要在视图控制器中存储选中"的单元格.你可以自己存储它,或者使用 tableView 的 didSelectRowAtIndexPath 方法.

However, you'll need to store which cell is 'checked' in your view controller if you want the checkbox to be selected after scrolling the tableView. You can store this yourself, or use the tableView's didSelectRowAtIndexPath method.

这篇关于重用单元格效果不佳 - TableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆