Why do all backgrounds disappear on UITableViewCell select?

20,074

Solution 1

What is happening is that each subview inside the TableViewCell will receive the setSelected and setHighlighted methods. The setSelected method will remove background colors but if you set it for the selected state it will be corrected.

For example if those are UILabels added as subviews in your customized cell, then you can add this to the setSelected method of your TableViewCell implementation code:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    self.textLabel.backgroundColor = [UIColor blackColor];

}

where self.textLabel would be whatever those labels are that are shown in the picture above

I'm not sure where your adding your selected view, I usually add it in the setSelected method.

Alternatively, you can subclass the UILabel and override the setHighlighted method like so:

-(void)setHighlighted:(BOOL)highlighted
{
    [self setBackgroundColor:[UIColor blackColor]];
}

Solution 2

The cell highlighting process can seem complex and confusing if you don't know whats going on. I was thoroughly confused and did some extensive experimentation. Here's the notes on my findings that may help somebody (if anyone has anything to add to this or refute then please comment and I will endeavour to confirm and update)

In the normal “not selected” state

  • The contentView (whats in your XIB unless you coded it otherwise) is drawn normally
  • The selectedBackgroundView is HIDDEN
  • The backgroundView is visible (so provided your contentView is transparent you see the backgroundView or (if you have not defined a backgroundView you'll see the background colour of the UITableView itself)

A cell is selected, the following occurs immediately with-OUT any animation:

  • All views/subviews within the contentView have their backgroundColor cleared (or set to transparent), label etc text color's change to their selected colour
  • The selectedBackgroundView becomes visible (this view is always the full size of the cell (a custom frame is ignored, use a subview if you need to). Also note the backgroundColor of subViews are not displayed for some reason, perhaps they're set transparent like the contentView). If you didn't define a selectedBackgroundView then Cocoa will create/insert the blue (or gray) gradient background and display this for you)
  • The backgroundView is unchanged

When the cell is deselected, an animation to remove the highlighting starts:

  • The selectedBackgroundView alpha property is animated from 1.0 (fully opaque) to 0.0 (fully transparent).
  • The backgroundView is again unchanged (so the animation looks like a crossfade between selectedBackgroundView and backgroundView)
  • ONLY ONCE the animation has finished does the contentView get redrawn in the "not-selected" state and its subview backgroundColor's become visible again (this can cause your animation to look horrible so it is advisable that you don't use UIView.backgroundColor in your contentView)

CONCLUSIONS:

If you need a backgroundColor to persist through out the highlight animation, don't use the backgroundColor property of UIView instead you can try (probably with-in tableview:cellForRowAtIndexPath:):

A CALayer with a background color:

UIColor *bgColor = [UIColor greenColor];
CALayer* layer = [CALayer layer];
layer.frame = viewThatRequiresBGColor.bounds;
layer.backgroundColor = bgColor.CGColor;
[cell.viewThatRequiresBGColor.layer addSublayer:layer];

or a CAGradientLayer:

UIColor *startColor = [UIColor redColor];
UIColor *endColor = [UIColor purpleColor];
CAGradientLayer* gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = viewThatRequiresBGColor.bounds;
gradientLayer.colors = @[(id)startColor.CGColor, (id)endColor.CGColor];
gradientLayer.locations = @[[NSNumber numberWithFloat:0],[NSNumber numberWithFloat:1]];
[cell.viewThatRequiresBGColor.layer addSublayer:gradientLayer];

I've also used a CALayer.border technique to provide a custom UITableView seperator:

// We have to use the borderColor/Width as opposed to just setting the 
// backgroundColor else the view becomes transparent and disappears during 
// the cell's selected/highlighted animation
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];

Solution 3

When you start dragging a UITableViewCell, it calls setBackgroundColor: on its subviews with a 0-alpha color. I worked around this by subclassing UIView and overriding setBackgroundColor: to ignore requests with 0-alpha colors. It feels hacky, but it's cleaner than any of the other solutions I've come across.

@implementation NonDisappearingView

-(void)setBackgroundColor:(UIColor *)backgroundColor {
    CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
    if (alpha != 0) {
        [super setBackgroundColor:backgroundColor];
    }
}

@end

Then, I add a NonDisappearingView to my cell and add other subviews to it:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cell";    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        UIView *background = [cell viewWithTag:backgroundTag];
        if (background == nil) {
            background = [[NonDisappearingView alloc] initWithFrame:backgroundFrame];
            background.tag = backgroundTag;
            background.backgroundColor = backgroundColor;
            [cell addSubview:background];
        }

        // add other views as subviews of background
        ...
    }
    return cell;
}

Alternatively, you could make cell.contentView an instance of NonDisappearingView.

Solution 4

My solution is saving the backgroundColor and restoring it after the super call.

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

You also need to do the same thing with -setHighlighted:animated:.

Solution 5

Found a pretty elegant solution instead of messing with the tableView methods. You can create a subclass of UIView that ignores setting its background color to clear color. Code:

class NeverClearView: UIView {
    override var backgroundColor: UIColor? {
        didSet {
            if UIColor.clearColor().isEqual(backgroundColor) {
                backgroundColor = oldValue
            }
        }
    }
}

Obj-C version would be similar, the main thing here is the idea

Share:
20,074
epologee
Author by

epologee

Independent software engineer, clean coder, spare-time inventor, teacher, math tutor, snow boarder and IKO certified kite surf instructor. @epologee

Updated on July 09, 2022

Comments

  • epologee
    epologee almost 2 years

    My current project's UITableViewCell behavior is baffling me. I have a fairly straightforward subclass of UITableViewCell. It adds a few extra elements to the base view (via [self.contentView addSubview:...] and sets background colors on the elements to have them look like black and grey rectangular boxes.

    Because the background of the entire table has this concrete-like texture image, each cell's background needs to be transparent, even when selected, but in that case it should darken a bit. I've set a custom semi-transparent selected background to achieve this effect:

    UIView *background = [[[UIView alloc] initWithFrame:self.bounds] autorelease];
    background.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    background.opaque = NO;
    
    [self setSelectedBackgroundView:background];
    

    And although that yields the right look for the background, a weird side effect happens when I select the cell; all other backgrounds are somehow turnt off. Here's a screenshot. The bottom cell looks like it should and is not selected. The top cell is selected, but it should display the black and grey rectangular areas, yet they are gone!

    Screenshot of the simulator. The top cell is selected, the bottom is not.

    Who knows what's going on here and even more important: how can I correct this?

  • epologee
    epologee about 12 years
    Hey there, thanks for answering this one. Must have gotten you a badge of some kind, since it has been unanswered for quite some time. Thanks!
  • epologee
    epologee about 12 years
    Thanks for the addition, interesting solution. I can't see why Apple ever decided to implement this subview background color behavior. Cheers!
  • Wirsing
    Wirsing about 11 years
    Works like a charm! Thanks!!
  • roberto.buratti
    roberto.buratti about 10 years
    Mitical :-) …But is it not enough to act on the layer of the view instead of creating a new one? Simply something like viewThatRequiresBGColor.layer = bgColor.CGColor;
  • Nat
    Nat over 9 years
    Don't forget to call super setHighlighted in the second method btw ;)
  • 1337holiday
    1337holiday over 9 years
    Hmm, setSelected does not seem to work in iOS 8 but setHighlighted override works, thanks!
  • Benjohn
    Benjohn over 8 years
    Worth a mention that backgroundView is only available for a UITableViewCell in the UITableViewStyleGrouped style.
  • Benjohn
    Benjohn over 8 years
    Heh – that's what I did after looking at the other answers. Seems to work well.
  • Devashis Kant
    Devashis Kant almost 8 years
    Thanks a lot. I had a similar issue. This helped me to resolve it.
  • Pedro Paulo Amorim
    Pedro Paulo Amorim almost 7 years
    Why Apple? WHY?