0

Util在 swift 中使用一个类作为助手类。除了函数之外,我还想用自定义颜色实现一些常量。

以这种方式使用 Struct 是否正确?

class Util: NSObject {

struct Colors {
    static let white = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
    static let orangeCantaloupe = UIColor(red: 1, green: 204/255, blue: 102/255, alpha: 1)
    static let greyMercury = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
    static let greyMagnesium = UIColor(red: 179/255, green: 179/255, blue: 179/255, alpha: 1)

}

class func anyFunction() {

.......
 }
}
4

1 回答 1

1

UIColor您可以使用新颜色进行扩展:

extension UIColor {
   static let white = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
   static let orangeCantaloupe = UIColor(red: 1, green: 204/255, blue: 102/255, alpha: 1)
   static let greyMercury = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1)
   static let greyMagnesium = UIColor(red: 179/255, green: 179/255, blue: 179/255, alpha: 1)
}

UIColor预期 a 的上下文中,可以隐含类型,因此您可以只写something.color = .orangeCantaloupe

或者,您可以将它们保存在单独的名称空间中(为了方便起见),例如BrandColors. 空枚举效果最好,因此您知道没有人会意外实例化无意义的对象。

于 2020-01-22T23:56:39.883 回答