user10264570
user10264570

Reputation:

Table view cell background not changing wholly

See Screenshot

I am trying to change the background color of a selected cell to white. However I see that some areas are still in grey. How do I avoid this?

self.tableView.selectRow(at: defaultLangIndexPath, animated: true, scrollPosition: .bottom)
    let selectedCell:UITableViewCell = tableView.cellForRow(at: defaultLangIndexPath)!
    selectedCell.contentView.backgroundColor = UIColor.white
    selectedCell.accessoryView?.backgroundColor = UIColor.white

I cannot unselect the cell because I want the highlighted accessory image and want it to work as expected.

Upvotes: 0

Views: 725

Answers (2)

Hardik Modha
Hardik Modha

Reputation: 9

To solve this UITableViewCell has a property called selectedBackgroundView which is nil at the initialization.

So you can initialize it with simple UIView() and set the background color of selectedBackgroundView in tableViewCell’s setSelected: method.

class SelectionCell: UITableViewCell {
  func awakeFromNib() { 
    ...
    self.selectedBackgroundView = UIView()
    // this view can be initialised in awakeFromNib 
       or UITableViewCell's initialiser methods.
    ...
  }

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

    super.setSelected(selected, animated: animated)
    self.selectedBackgroundView?.backgroundColor = selected ? .white : .clear
    ...
  }
}

Upvotes: 1

alegelos
alegelos

Reputation: 2614

Swift 4

A: By setting it in Storyboard

Go to Storyboard, select the cell, go to attribute inspector (at the top right), on selection, set None

enter image description here

B: By Cell Subclass

Make sure to set this custom cell type on your Storyboard Identity Inspector or programatically.

class WhiteBackgroundCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        selectionStyle = .none
        //or for custom color
        //let background View = UIView()
        //backgroundView.backgroundColor = .white
        //selectedBackgroundView = backgroundView

        //other cell setting
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        //do something
    }
}

C: By TableViewDelegate

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    guard let cell = tableView.cellForRow(at: indexPath)else{return}
    cell.backgroundColor = UIColor.white
}

Options A and B are fine. Option C is not a good practice, but not sure what u want to achieve. Since that delegate is intended to do some logic/triggers, not setting cell background. Plus u will need to change background color to normal state and deselected.

Upvotes: 0

Related Questions