How can I create a UIColor from a hex string?

后端 未结 30 1679
北恋
北恋 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

    For swift 2.0+. This code works fine to me.

    extension UIColor {
        /// UIColor(hexString: "#cc0000")
        internal convenience init?(hexString:String) {
            guard hexString.characters[hexString.startIndex] == Character("#") else {
                return nil
            }
            guard hexString.characters.count == "#000000".characters.count else {
                return nil
            }
            let digits = hexString.substringFromIndex(hexString.startIndex.advancedBy(1))
            guard Int(digits,radix:16) != nil else{
                return nil
            }
            let red = digits.substringToIndex(digits.startIndex.advancedBy(2))
            let green = digits.substringWithRange(Range(start: digits.startIndex.advancedBy(2),
                end: digits.startIndex.advancedBy(4)))
            let blue = digits.substringWithRange(Range(start:digits.startIndex.advancedBy(4),
                end:digits.startIndex.advancedBy(6)))
            let redf = CGFloat(Double(Int(red, radix:16)!) / 255.0)
            let greenf = CGFloat(Double(Int(green, radix:16)!) / 255.0)
            let bluef = CGFloat(Double(Int(blue, radix:16)!) / 255.0)
            self.init(red: redf, green: greenf, blue: bluef, alpha: CGFloat(1.0))
        }
    }
    

    This code includes string format checking. e.g.

    let aColor = UIColor(hexString: "#dadada")!
    let failed = UIColor(hexString: "123zzzz")
    

    And as far as I know, my code is of no disadvantage for its maintaining the semantic of failible condition and returning an optional value. And this should be the best answer.

提交回复
热议问题