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.
Swift 3, 4, 5 select cell background colour
1) Change only highlighted colour when user click on cell:
1.1) Inside cell class:
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.init(white: 1.0, alpha: 0.1)
selectedBackgroundView = backgroundView
}
1.2) Viewcontroller that you use customized cell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
2) If you to set colour for selected cells:
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
if selected {
self.backgroundColor = .darkGray
} else {
self.backgroundColor = .white
}
}
This worked perfectly with grouped calls: Implement a custom subclass of UITableViewCell
This will respect corners and such...
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
if(selected)
[self setBackgroundColor:[UIColor colorWithRed:(245/255.0) green:(255/255.0) blue:(255/255.0) alpha:1]];
else
[self setBackgroundColor:[UIColor whiteColor]];
}
Create a custom UITableViewCell. Inside you custom class override the "setSelected" function and change the contentView background color. You can also override you "setHighlighted" function.
In Swift:
class myTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
// Add your color here
self.contentView.backgroundColor = UIColor.whiteColor()
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
// Add your color here
self.contentView.backgroundColor = UIColor.whiteColor()
}
}
If you're talking about selected cells, the property is -selectedBackgroundView
. This will be shown when the user selects your cell.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.contentView.backgroundColor = .black
} else {
self.contentView.backgroundColor = .white
}
}
- (void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor yellowColor];
}
- (void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = nil;
}