How can I create a UIColor from a hex string?

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

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

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 17:33

    extension UIColor 
    {
        class func fromHexaString(hex:String) -> UIColor
        {
            let scanner           = Scanner(string: hex)
            scanner.scanLocation  = 0
            var rgbValue: UInt64  = 0
            scanner.scanHexInt64(&rgbValue)
    
            return UIColor(
                red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
                green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
                blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
                alpha: CGFloat(1.0)
            )
        }
    }
    
    //you can call like this.
    
    UIColor.fromHexaString(hex:3276b1)
    

提交回复
热议问题