UITableViewCell makes label's background clear when highlighted

You need to subclass UITableViewCell and override the following two methods:

Objective-C:

- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated
{
    UIColor *backgroundColor = self.myLabel.backgroundColor;
    [super setHighlighted:highlighted animated:animated];
    self.myLabel.backgroundColor = backgroundColor;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    UIColor *backgroundColor = self.myLabel.backgroundColor;
    [super setSelected:selected animated:animated];
    self.myLabel.backgroundColor = backgroundColor;
}

Swift

override func setSelected(_ selected: Bool, animated: Bool) {
    let color = myLabel.backgroundColor
    super.setSelected(selected, animated: animated)
    myLabel.backgroundColor = color
}

override func setHighlighted(_ highlighted: Bool, animated: Bool) {
    let color = myLabel.backgroundColor
    super.setHighlighted(highlighted, animated: animated)
    myLabel.backgroundColor = color
}

Another way to keep the background color from changing on highlight is to set the backgroundColor property on the label's layer instead of on the label itself.

#import <QuartzCore/QuartzCore.h>

...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Get a table cell
    UITableViewCell *cell = [tableView dequeueReusableCellForIdentifier:@"cell"];

    // Set up the table cell
    cell.textLabel.text = @"This is a table cell.";

    // If you're targeting iOS 6, set the label's background color to clear
    // This must be done BEFORE changing the layer's backgroundColor
    cell.textLabel.backgroundColor = [UIColor clearColor];

    // Set layer background color
    cell.textLabel.layer.backgroundColor = [UIColor blueColor].CGColor;

    return cell;
}

The layer is not affected by cell highlighting or selection.


Alternatively subclass the label you don't want to change color:

@interface PersistentBackgroundLabel : UILabel {
}

- (void)setPersistentBackgroundColor:(UIColor*)color;

@end


@implementation PersistentBackgroundLabel

- (void)setPersistentBackgroundColor:(UIColor*)color {
    super.backgroundColor = color;
}

- (void)setBackgroundColor:(UIColor *)color {
    // do nothing - background color never changes
}

@end

Then set the color once explicitly using setPersistentBackgroundColor:. This will prevent background color changes from anywhere without using your custom explicit background color change method.

This has the advantage of also eliminating clear background in label during transitions.