Search code examples
iosobjective-cuitableviewuiappearance

Change the text colors of all UITableViewCells using UIAppearance


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.


Solution

  • 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.