jhaywoo8
jhaywoo8

Reputation: 767

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

}

Upvotes: 7

Views: 14823

Answers (5)

Amr AbdelWahab
Amr AbdelWahab

Reputation: 115

you can set the Selected Background view in awakeFromNib method

class MyCell: UITableViewCell {
     override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
            selectedBackgroundView = {
                let view = UIView.init()
                view.backgroundColor = .white
                return view
            }()
        }
}

Upvotes: 3

Ashish
Ashish

Reputation: 726

In your UITableViewCell class use following code for change selected cell background view color

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

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

Upvotes: -1

Daniel Isaac
Daniel Isaac

Reputation: 745

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

Upvotes: 18

Flickerlight
Flickerlight

Reputation: 984

You can do background color change in either your "willSelect" or "didSelect" method. For example:

override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    let cell = tableView.cellForRow(at: indexPath)!
    cell.contentView.superview?.backgroundColor = UIColor.blue
    return indexPath        
}

Upvotes: 0

Tanddd
Tanddd

Reputation: 47

Maybe you need this:

cell.selectedBackgroundView

Upvotes: 2

Related Questions