1

我希望能够在选择单元格时突出显示我的自定义单元格文本标签目前我可以突出显示它们,但是当我向下滚动表格时,我没有选择的其他几个单元格标签也被突出显示。

我知道这可能与出队可重复使用的单元格有关,但我无法修复它。

我曾尝试使用 didSelectRowAt 函数方法,我还尝试允许我的 tableview 进行多项选择并在我的 customCell 类中使用 setSelected 函数

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            let cell = tableView.cellForRow(at: indexPath) as! RecommendationCell


            if cell.isSelected {
                if cell.label.textColor == UIColor.highlightColor {
                    cell.label.textColor = .white
                } else  {
                    cell.label.textColor = UIColor.highlightColor
                }
            }
}


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        if selected {
            self.label.textColor = UIColor.highlightColor
        }

    }
4

1 回答 1

0

UITableView这是由于将重用单元格的事实。

您必须在 中更新单元格(在您的情况下为背景颜色)状态tableView:willDisplayCell:forRowAtIndexPath:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
    self.label.textColor = cell.isSelected ? UIColor.highlightColor : UIColor.label
}

一个更优雅的解决方案是prepareForReuse在您的自定义单元格类中覆盖 (选择任何一个)。

class RecommendationCell : UITableViewCell
{
    override func prepareForReuse()
    {
        super.prepareForReuse()

        self.label.color = self.isSelected ? UIColor.highlight : UIColor.label
    }
}

您可以在官方文档中阅读有关prepareForReuse的更多信息。

于 2020-03-11T07:18:43.737 回答