Change text color of all UITableViewCells using UIAppearance

I cannot change the text colors of a UITableViewCell using the UIAppearance mechanism.

Here is my commentary code showing what works for me and what doesn't:

 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 works, but I cannot set different colors for plain text and long text.

Is there something I'm doing wrong?

PS Defining statics in Interface Builder will not work for me - I have themes that can be dynamically changed at runtime.

+5
source share
2 answers

You are doing the right thing, but there is no way for iOS to distinguish between these two labels using UIAppearance . You must either set the text color in willDisplayCell , or if you really want to use UIAppearance , create custom UILabel subclasses that you can customize more precisely.

If you want to use willDisplayCell , it will 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 can also find an answer containing other ideas.

+3
source

You can set the text color as follows.

 [cell.textLabel setTextColor:[UIColor whiteColor]]; [cell.detailTextLabel setTextColor:[UIColor redColor]]; 
+1
source

Source: https://habr.com/ru/post/1238036/


All Articles