【问题标题】:UITableViewCell selection backgroundColor change not workingUITableViewCell 选择背景颜色更改不起作用
【发布时间】:2019-04-05 10:59:40
【问题描述】:

我有一个自定义的 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() 的两个陈述总是错误的。 backgroundColor 永远不会改变。我在这里做错什么了吗?

【问题讨论】:

  • 你设置了tableview属性tableView.allowsSelection = true吗?

标签: ios swift uitableview uikit


【解决方案1】:

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

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

【讨论】:

  • 你能解释一下这有什么帮助吗?似乎您只是建议使用三元而不是 if 将有助于解决 OP 的问题。
  • @Nate 您只需从 CustomTableViewCelltableView.deselectRow(at: indexPath, animated: true) 中删除所有代码并替换 CustomTableViewCell使用我的代码编写代码并在单击时检查它会自动以红色背景突出显示。
【解决方案2】:

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

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

    self.contentView.backgroundColor = .red

而不是

    self.backgroundColor = .red

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

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

}

请参阅下面附加的演示应用程序源代码。如果需要任何进一步的帮助。

Source Code

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2014-04-09
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    相关资源
    最近更新 更多