Custom UI TableViewCell selected backgroundcolor swift

I have a likeness problem. In your cellForRowAtIndexPath method set:

cell.selectionStyle = .None

and then set didHighlightRowAtIndexPath...

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .green
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .clear
}

My two cents: the proper way of doing it (also visually) is to use the designated view in a (tableView)cell, that is the selectedBackgroundView property. However, you need to initialize it first with UIView()

SWIFT 3.0

override func awakeFromNib() {
    super.awakeFromNib()
    self.selectedBackgroundView = UIView()
    self.selectionStyle = .default // you can also take this line out
}

Then you can use it in your customized cell as follows:

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
    self.selectedBackgroundView!.backgroundColor = selected ? .red : nil
}

That's it. Of course you can also integrate the above in your UITableView functions referred to above. Check it out.


You've the right method already in there: didSelectRowAtIndexPath. In that method you can call tableView.cellForRowAtIndexPath(indexPath) and get your cell. Than you can set the cell-background to your color:

 func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        println("Row \(indexPath.row) selected")
        let cell:YourCustomCell = tableView.cellForRowAtIndexPath(indexPath) as YourCell
        cell.backgroundColor = UIColor.redColor()
    }

Or, a better way would be to check in your cellForRowAtIndexPath method, if a cell is selected:

if(cell.selected){
  cell.backgroundColor = UIColor.redColor()
}else{
  cell.backgroundColor = UIColor.clearColor()
}

Update for Swift 3

This answer is based on Cao Yong answer, and it is intended as an update for Swift 3

For Swift 3, use the following code in your cellForRowAt indexPath method set:

cell.selectionStyle = .none

Then, set it in didHighlightRowAtIndexPath

func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .red
}

func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
    let cell  = tableView.cellForRow(at: indexPath)
    cell!.contentView.backgroundColor = .clear
}