UIAppearance 对 Label 文本颜色没有影响

UIAppearance has no effect on Label text color

我正在使用 UIAppearance 设置我应用中所有标签的文本颜色。然而文字颜色没有改变。

这是我如何创建标签的示例

//show the loading message
MessageLabel *messageLabel = [[MessageLabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
messageLabel.text = @"\n\nLoading ...\n\n";
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = NSTextAlignmentCenter;
[messageLabel sizeToFit];
self.tableview.backgroundView = messageLabel;

这是我设置文本颜色的方法

[[MessageLabel appearance] setTextColor:[UIColor blackColor]];

需要注意的是所有这些 MessageLabel 都是 UITableView

的 BackgroundViews

来自文档:

iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.

参考 this,UIAppearance 似乎与 UILabel 不兼容...

因为你是 UILabel 的子class,也许在你的 中设置 textcolor 属性 initWithFrame: 方法是有意义的MessageLabel class?

或者另一种选择,因为你说这些 MessageLabel 实例用于 UITableViewCell 的背景,也许让标签的背景保持清晰并更改单元格本身的背景是有意义的,例如在 tableView 委托的 tableView:willDisplayCell:forRowAtIndexPath: 方法中?

如果您在代码中实例化了 UILabel,则必须在设置外观后手动设置 textColor 属性。

messageLabel.textColor = [[UILabel appearance] textColor];

如前所述,UILabel 的 textColor 不适用于 UIAppearance。我通过添加一个只包装 textColor 的 UIAppearance 兼容 属性 来解决这个问题。在 Swift 这看起来像

class MessageLabel: UILabel {

    @objc dynamic var configurableTextColor: UIColor {
        get {
            return textColor
        }
        set {
            textColor = newValue
        }
    }

    ...
}

然后配置外观:

MessageLabel.appearance().configurableTextColor = .black