Search code examples
iosuitableviewswiftselectionselected

UITableViewCell Selected Background Color on Multiple Selection


// Doesn't work
cell.selectionStyle = .Blue
//Works when the selection is not multiple, if it's multiple with each selection the previous one disappear...
let cellBGView = UIView()
cellBGView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.4)
cell.selectedBackgroundView = cellBGView

Any answer how to set background color of the cells which are selected?


Solution

  • Swift 4.2

    For multiple selections you need to set the UITableView property allowsMultipleSelection to true.

    myTableView.allowsMultipleSelection = true

    In case you subclassed the UITableViewCell, you override setSelected(_ selected: Bool, animated: Bool) method in your custom cell class.

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