How can I create a UIColor from a hex string?

后端 未结 30 1611
北恋
北恋 2020-11-22 16:53

How can I create a UIColor from a hexadecimal string format, such as #00FF00?

30条回答
  •  一向
    一向 (楼主)
    2020-11-22 17:24

    I created a convenience init for that:

    extension UIColor {
    convenience init(hex: String, alpha: CGFloat)
    {
        let redH = CGFloat(strtoul(hex.substringToIndex(advance(hex.startIndex,2)), nil, 16))
        let greenH = CGFloat(strtoul(hex.substringWithRange(Range(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4))), nil, 16))
        let blueH = CGFloat(strtoul(hex.substringFromIndex(advance(hex.startIndex,4)), nil, 16))
    
        self.init(red: redH/255, green: greenH/255, blue: blueH/255, alpha: alpha)
    }
    }
    

    then you can create an UIColor anywhere in your project just like this:

    UIColor(hex: "ffe3c8", alpha: 1)
    

    hope this helps...

提交回复
热议问题