类型 'UIColor?' 没有成员“.myCustomColor” Swift 5.0

Type 'UIColor?' has no member ".myCustomColor" Swift 5.0

我所有的颜色都在一个专门的颜色资产中。这允许我定义支持 "Any Appearance" 和 "Dark Appearance" 的命名常量。现有颜色资产有效(以前定义),但如果我尝试定义新资产(例如 myCustomColor)或什至复制现有资产,那么我会得到:

Type 'UIColor?' has no member 'myCustomColor'

示例用法:

label.textColor = .myCustomColor

我知道我可以使用(用新创建的颜色测试,所以没有错别字):

UIColor(named: "myCustomColor")

但是,我不想更改此语法或让不同的语法使我的代码混乱。

我正在使用 Xcode 11.3 (11C29) 并使用 Swift 5. 还有其他人遇到同样的问题吗?

您需要在 UIColor 的扩展中声明自定义颜色。

extension UIColor {
    static let myCustomColor = UIColor(named: "myCustomColor")
}

然后您可以如下使用此颜色:

label.textColor = UIColor.myCustomColor

这里没有“问题”。与 Apple 的 UIColor.systemRed 类似的静态 属性 UIColor.myCustomColor 永远不会 spring 神奇地存在,只是因为您将颜色集放入资产目录中。如果你想要这样一个 属性 你必须明确地定义它。