使用 UIAppearance 更改所有 UITableViewCells 的文本颜色

Change the text colors of all UITableViewCells using UIAppearance

我无法使用 UIAppearance 机制更改 UITableViewCell 的文本颜色。

这是我的代码,其中的注释显示了哪些对我有效,哪些无效:

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

如您所见,第二种方法是可行的,但我无法为普通文本和详细文本设置不同的颜色。

我做错了什么吗?

P.S。在 Interface Builder 中静态定义内容对我不起作用 - 我有可以在 运行 时间内动态更改的主题。

您做的是对的,但是 iOS 无法使用 UIAppearance 区分这两个标签。您应该在 willDisplayCell 中设置文本颜色,或者,如果您真的想使用 UIAppearance,请创建您可以更准确定位的自定义 UILabel 子类。

如果你想使用 willDisplayCell,它看起来像这样:

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

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

您可以像这样设置文本颜色。

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