Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the background color of a UILabel within a UITableViewCell

A UITableViewCell comes "pre-built" with a UILabel as its one and only subview after you've init'ed it. I'd really like to change the background color of said label, but no matter what I do the color does not change. The code in question:

UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;
like image 767
rpj Avatar asked Oct 21 '08 17:10

rpj


2 Answers

Your code snippet works fine for me, but it must be done after the cell has been added to the table and shown, I believe. If called from the initWithFrame:reuseIdentifier:, you'll get an exception, as the UILabel subview has not yet been created.

Probably the best solution is to add your own UILabel, configured to your standards, rather than relying on this (very rickety) path to the built-in one.

like image 192
Ben Gottlieb Avatar answered Sep 21 '22 06:09

Ben Gottlieb


This doesn't work because the UITableViewCell sets its label backgroundColors in the layoutSubviews method.

If you want to change the color of the built-in textLabel or detailTextLabel, subclass the UITableViewCell and override layoutSubviews. Call the super implementation, THEN change the backgroundColor property to what you want.

- (void) layoutSubviews
{   
     [super layoutSubviews];

     self.textLabel.backgroundColor = [UIColor redColor];
}
like image 44
TomSwift Avatar answered Sep 20 '22 06:09

TomSwift