How can I make a Swift enum with UIColor value?

前端 未结 9 750
深忆病人
深忆病人 2020-12-16 09:37

I\'m making a drawing app and I would like to refer to my colors through use of an enum. For example, it would be cleaner and more convenient to use Colors.RedColor

9条回答
  •  孤城傲影
    2020-12-16 10:10

    Actually I use such implementation, it is very convenience for me because of two reason, first one I can use dex value and another all colors in constant

    import UIKit
    
    struct ColorPalette {
    struct Gray {
        static let Light = UIColor(netHex: 0x595959)
        static let Medium = UIColor(netHex: 0x262626)
    }
    }
    
    extension UIColor {
    convenience init(red: Int, green: Int, blue: Int) {
        assert(red >= 0 && red <= 255, "Invalid red component")
        assert(green >= 0 && green <= 255, "Invalid green component")
        assert(blue >= 0 && blue <= 255, "Invalid blue component")
    
        self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
    }
    
    convenience init(netHex: Int) {
        self.init(red: (netHex >> 16) & 0xff, green: (netHex >> 8) & 0xff, blue: netHex & 0xff)
    }
    }
    

    usage

    let backgroundGreyColor = ColorPalette.Gray.Medium.cgColor
    

提交回复
热议问题