Change the text colors of all UITableViewCells using UIAppearance
Asked Answered
L

2

7

I am not able to change the text colors of a UITableViewCell using UIAppearance mechanism.

Here is my code with comments showing what is working for me and what is not:

UITableViewCell *cell = [UITableViewCell appearance];
cell.backgroundColor = [UIColor blueColor]; // working
cell.textLabel.textColor = [UIColor whiteColor]; // NOT WORKING
cell.detailTextLabel.textColor = [UIColor redColor]; // NOT WORKING

UILabel *cellLabel = [UILabel appearanceWhenContainedIn:[UITableViewCell class], nil];
cellLabel.textColor = [UIColor whiteColor]; // working

As you can see, the second way is working, but I cannot set different colors to normal text and detail text.

Is there something that I am doing wrong?

P.S. Defining stuff statically in Interface Builder will not work for me - I have themes which can be changed dynamically during run time.

Les answered 13/12, 2015 at 20:43 Comment(0)
D
4

You're doing the right thing, but there's no way for iOS to distinguish between those two labels using UIAppearance. You should either set the text colour in willDisplayCell, or, if you really want to use UIAppearance, create custom UILabel subclasses that you can target more accurately.

If you want to use willDisplayCell, it would look something like this:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.textLabel.textColor = [UIColor blackColor];
    cell.detailTextLabel.textColor = [UIColor redColor];
}

Alternatively, you might also find this answer has some other ideas.

Disherison answered 13/12, 2015 at 20:49 Comment(1)
I need a small clarification - I created only one UILabel subclass for detailed text, say MyLabel. Then I tried to color UILabel appearance and MyLabel appearance, giving both the same class hierarchy. The problem is that the UILabel color is always "winning" and MyLabel color is never applied. Any thoughts on how are the conditions evaluated?Les
S
1

you can set the the text colour like this.

[cell.textLabel setTextColor:[UIColor whiteColor]];
[cell.detailTextLabel setTextColor:[UIColor redColor]];
Saire answered 14/12, 2015 at 6:19 Comment(3)
As I mentioned in my post - it is not working. I guess there is no difference between [cell.textLabel setTextColor:[UIColor whiteColor]]; and cell.textLabel.textColor = [UIColor whiteColor]; // NOT WORKINGLes
you can try to get the label from view UILabel *label=(UILabel *)[cell.contentView viewWithTag:yourLabelTag]; then set the text color.Saire
It is an appearance proxy, it doesn't have any contentView.Les

© 2022 - 2024 — McMap. All rights reserved.