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.
For iOS7+ and if you are using Interface Builder then subclass your cell and implement:
Objective-C
- (void)awakeFromNib {
[super awakeFromNib];
// Default Select background
UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
self.selectedBackgroundView = v;
}
Swift 2.2
override func awakeFromNib() {
super.awakeFromNib()
// Default Select background
self.selectedBackgroundView = { view in
view.backgroundColor = .redColor()
return view
}(UIView())
}
The default style is gray and it destroys the colors of the cell if it was done programmatically. You can do this to avoid that. (in Swift)
cell.selectionStyle = .None
Check out AdvancedTableViewCells
in Apple's sample code.
You'll want to use the composite cell pattern.
I was able to solve this problem by creating a subclass of UITableViewCell
and implementing the setSelected:animated: method
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
if(selected) {
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
[self setBackgroundColor:[UIColor greenColor]];
} else {
[self setBackgroundColor:[UIColor whiteColor]];
}
}
The trick was setting the
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
in the implementing view controller and then in the tableViewCell setting it as
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
Hope this helps. :)
If you just want to remove the grey background color do this :
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[tableView cellForRowAtIndexPath:indexPath] setSelectionStyle:UITableViewCellSelectionStyleNone];
}
in Swift 3, converted from illuminates answer.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if(selected) {
self.selectionStyle = .none
self.backgroundColor = UIColor.green
} else {
self.backgroundColor = UIColor.blue
}
}
(however the view only changes once the selection is confirmed by releasing your finger)