How can I create a UIColor from a hex string?

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

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

30条回答
  •  生来不讨喜
    2020-11-22 17:31

    SWIFT 4

    You can create a nice convenience constructor in the extension like this:

    extension UIColor {
        convenience init(hexString: String, alpha: CGFloat = 1.0) {
            var hexInt: UInt32 = 0
            let scanner = Scanner(string: hexString)
            scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
            scanner.scanHexInt32(&hexInt)
    
            let red = CGFloat((hexInt & 0xff0000) >> 16) / 255.0
            let green = CGFloat((hexInt & 0xff00) >> 8) / 255.0
            let blue = CGFloat((hexInt & 0xff) >> 0) / 255.0
            let alpha = alpha
    
            self.init(red: red, green: green, blue: blue, alpha: alpha)
        }
    }
    

    And use it later like

    let color = UIColor(hexString: "#AABBCCDD")
    

提交回复
热议问题