Haagenti
Haagenti

Reputation: 8154

UITableView cell selection

I've got a UILabel with a background color in a cell. When I select this cell, the cell changes the color (which it should) but it also changes the background of the label. I want the preserve the background color on the UILabel. When I use an image with just a random color in it it is preserved, but isn't there any better way?

Thanks in advance

Code:

    _label = [UILabel new];
    _label.translatesAutoresizingMaskIntoConstraints = NO;
    _label.font = [UIFont systemFontOfSize:10.f];
    _label.backgroundColor = HEXCOLOR(0xFFE5E5E5); //Macro just a UIColor

But I use this way to add a different selection color (could have something to do with it)

    UIView *selectionColor = [[UIView alloc] init];
    selectionColor.backgroundColor = HEXCOLOR(0XFFF1F1F1);
    self.selectedBackgroundView = selectionColor;
    self.contentView.backgroundColor = [UIColor whiteColor];

Nothing really more to it. Just a simple label added with autolayout to fill with a padding of 5.

Solution: Create a subclass of UILabel and just not call super

- (instancetype) initWithColor:(UIColor *)color
{
    self = [super init];
    if (self) {
         [super setBackgroundColor:color];
    }
    return self;
}

- (void) setBackgroundColor:(UIColor *)backgroundColor
{
    //do nothing here!   
}

Upvotes: 0

Views: 93

Answers (1)

fluidsonic
fluidsonic

Reputation: 4676

The default behavior of UITableView is that when a cell is selected the background color of all the cell's subviews is temporarily removed.

We usually handled this issue by subclassing UILabel, overwrite setBackgroundColor: and simply do not call [super setBackgroundColor:] after we've set our own color.

@interface MyLabel : UILabel

@property(nonatomic) BOOL backgroundColorLocked;

@end


@implementation MyLabel

-(void) setBackgroundColor:(UIColor*)backgroundColor {
    if (_backgroundColorLocked) {
        return;
    }

    super.backgroundColor = backgroundColor;
}

@end

Usage:

MyLabel* label = …;
label.backgroundColor = UIColor.redColor;
label.backgroundColorLocked = YES;

As long as backgroundColorLocked is YES no-one, not even UITableView(Cell), can change the label's background color.

Upvotes: 1

Related Questions