Does anyone know how to change the background color of a cell using UITableViewCell, for each selected cell? I created this UITableViewCell inside the code for TableView.
In Swift
let v = UIView()
v.backgroundColor = self.darkerColor(color)
cell?.selectedBackgroundView = v;
...
func darkerColor( color: UIColor) -> UIColor {
var h = CGFloat(0)
var s = CGFloat(0)
var b = CGFloat(0)
var a = CGFloat(0)
let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
if hueObtained {
return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a)
}
return color
}
Works for me
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
For a solution that works (properly) with UIAppearance
for iOS 7 (and higher?) by subclassing UITableViewCell
and using its default selectedBackgroundView
to set the color, take a look at my answer to a similar question here.
I've had luck with the following:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
bool isSelected = // enter your own code here
if (isSelected)
{
[cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
[cell setAccessibilityTraits:UIAccessibilityTraitSelected];
}
else
{
[cell setBackgroundColor:[UIColor clearColor]];
[cell setAccessibilityTraits:0];
}
}
Swift 5.3
Here I did for a single row without creating a class for the cell.
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.contentView.backgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)
}
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.contentView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
}
I created UIView and set the property of cell selectedBackgroundView:
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;