Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change selected color for table view cell?

When I select on a cell on my table view, it changes into this white color. I want to change it.

enter image description here

I tried using an if statement but it didn't work.

Here is the code that I used.

override func tableView(_ tableView: UITableView, cellForRowAt 
indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)

    if cell.isSelected == true {
        cell.backgroundColor = .blue
    } else {
        cell.backgroundColor = .red
    }

    return cell

}
like image 407
jhaywoo8 Avatar asked Jun 26 '17 03:06

jhaywoo8


2 Answers

You can do either one of this -

  1. Change the selectionStyle property of your cell.

For example: If you change it to UITableViewCellSelectionStyleGray, it will be gray.

 cell.selectionStyle = UITableViewCellSelectionStyleGray;
  1. Change the selectedBackgroundView property.

    let bgColorView = UIView()
    bgColorView.backgroundColor = UIColor.red
    cell.selectedBackgroundView = bgColorView
    

swift 4 correction:

    cell.selectionStyle = UITableViewCellSelectionStyle.gray
like image 74
Daniel Isaac Avatar answered Sep 24 '22 23:09

Daniel Isaac


Maybe you need this:

cell.selectedBackgroundView
like image 21
Tanddd Avatar answered Sep 25 '22 23:09

Tanddd