Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing UITableViewCell textLabel background color to clear

In my app I have a table view with customViewCells. I subclassed the UITableViewCell class and added an image that will load async and for the text I use cell.textLabel.text = @"someThext".

For the cells the background color is set alternatively to [UIColor darkGrayColor] and [UIColor whiteColor].

When I run the app in the simulator and on the phone the textLabel of the cell has the background white. I want to set it to be clear, because I want the background color of the cell to be full not a strip then white then another strip.

In the init method of my custom cell I added, hoping that the white will turn into red, but it doesn't have any effect:

[self.textLabel setBackgroundColor:[UIColor redColor]];

I tried also:

self.textLabel.backgroundColor = [UIColor redColor];

But this also didn't work... if I add a UILabel as a subview, the background color of the label can be set, but I don't want to do that because when I rotate the phone I want my labels to auto enlarge.

Any ideas why setting the background color of cell.textLabel doesn't work?

Thank you

like image 210
Sorin Antohi Avatar asked Jul 22 '09 10:07

Sorin Antohi


3 Answers

If you do not want to subclass UITableViewCell you can just add this:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
     [[cell textLabel] setBackgroundColor:[UIColor clearColor]];
     [[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
}
like image 190
plug-in Avatar answered Oct 24 '22 04:10

plug-in


The problem is that UIKit sets the cell background color in the -setSelected method. I had the method but didn't have self.textLabel.backgroundColor = [UIColor clearColor]; self.detailTextLabel.backgroundColor = [UIColor clearColor]; in it so I added them and the problem mentioned in the picture was fixed.

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.detailTextLabel.backgroundColor = [UIColor clearColor];
}
like image 23
Sorin Antohi Avatar answered Oct 24 '22 03:10

Sorin Antohi


Looks like Apple changed something here. Doing exactly this in iOS4 works:

self.textLabel.backgroundColor = [UIColor xxxColor];
self.detailTextLabel.backgroundColor = [UIColor xxxColor];

At least up to the point that the label background is transparent or takes the background color. Still not possible to set an own background color.

Nice that this is fixed, but a bit surprising during tests if you develop with base SDK 4.1 and min. deployment 3.1 for iPhone classic and iPad.

like image 3
Gerd Avatar answered Oct 24 '22 04:10

Gerd