如何更改表格单元格选择的颜色?

时间:2019-08-20 01:58:17

标签: uitableview

我设置了单元格的选定颜色,但是为什么当我第一次单击它时它仍然是默认的灰色?第二次单击将成为我定义的颜色。

我尝试为单元格设置背景色,但第一次单击时无效。

 override func tableView(_ tableView: UITableView,
                            didSelectRowAt indexPath: IndexPath) {
        if let cell = tableView.cellForRow(at: indexPath) {
            let backgroundView = UIView()
            backgroundView.backgroundColor = UIColor.blue
            cell.selectedBackgroundView = backgroundView

   }       

}

我想要我第一次单击时定义的颜色。

2 个答案:

答案 0 :(得分:0)

在调用 didSelectRowAt 方法之前,您必须更改 selectedBackgroundView

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
            let backgroundView = UIView()
            backgroundView.backgroundColor = UIColor.blue
            cell.selectedBackgroundView = backgroundView
        }
        return cell
    }

答案 1 :(得分:0)

如果您是UITableViewCell的子类,则可以在自定义tableview单元格类中重写setSelected(_ selected:Bool,animation:Bool)方法

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    if selected {
        contentView.backgroundColor = UIColor.green
    } else {
        contentView.backgroundColor = UIColor.blue
    }
}