在最近的项目中遇到了这样一个问题,需要枚举 UIColor,但是 Swift enum raw value 不能是 UIColor 类型,因此去网上看到了一个个人感觉很方便的解决方法。

// RGBA 16进制数
enum Colors: UInt32 {
    case red = 0xFF3B30FF
    case yellow = 0xFFCC00FF
    case blue = 0x007AFFFF
    case green = 0x4CD964FF
    case purple = 0x5856D6FF
    case lightBlue = 0x5AC8FAFF
    case brown = 0xB97437FF
    case white  = 0xFFFFFFFF
    case black = 0x000000FF
}

extension UIColor {
    convenience init(named name: Colors) {
        let rgbaValue = name.rawValue
        let red = CGFloat((rgbaValue >> 24) & 0xff) / 255.0
        let green = CGFloat((rgbaValue >> 16) & 0xff) / 255.0
        let blue  = CGFloat((rgbaValue >>  8) & 0xff) / 255.0
        let alpha = CGFloat((rgbaValue      ) & 0xff) / 255.0
        
        self.init(red: red, green: green, blue: blue, alpha: alpha)

    }
}

使用:

UIColor(named: .red)

原文链接:
https://toutiao.io/posts/203575/app_preview