UITableViewCell选择backgroundColor更改不起作用

时间:2019-04-05 10:59:40

标签: ios swift uitableview uikit

我有一个自定义的UITableViewCell类,如下所示:

class CustomTableViewCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.selectionStyle = .none
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        print("Selected: ", selected)

        if selected {
            self.backgroundColor = .red
        } else {
            self.backgroundColor = .white
        }
    }

    override func setHighlighted(_ highlighted: Bool, animated: Bool) {
        super.setHighlighted(highlighted, animated: animated)

        print("Highlighted: ", highlighted)

        if highlighted {
            self.backgroundColor = .red
        } else {
            self.backgroundColor = .white
    }
}

然后在我的UITableViewDelegate中添加以下代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    // Navigate to the next screen
}

但是,两个print()语句始终为false。 backgroundColor永远不会改变。我在这里做错什么了吗?

2 个答案:

答案 0 :(得分:0)

删除所有其他代码,只需将您的UITableViewCell类替换为此

class CustomTableViewCell: UITableViewCell {
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.backgroundColor = selected ? .red : .white
    }
}

答案 1 :(得分:0)

我在您的代码中发现了两个问题。请参考以下问题以及解决方法。

请使用以下代码设置UITableViewCell的背景色

    self.contentView.backgroundColor = .red

代替

    self.backgroundColor = .red

如果要永久更改颜色,只需替换didSelectRowAt方法,否则请保持不变。

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

}

请参阅下面所附的演示应用程序源代码。如果需要其他帮助。

Source Code