ios - How to create a hex color string UIColor initializer in Swift? -


this question has answer here:

i using code create uicolor hex value. working perfectly.

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:

var textcolor = uicolor(nethex: 0xffffff) 

this code works int hex code. needs hex code 0xffffff int type. having hex code web service. "#ffffff" (string not int). can convert string "0xffffff". can't convert "0xffffff"(string) 0xffffff (int).

i need

var textcolor = uicolor(nethex: "0xffffff") 

or better this:

var textcolor = uicolor(nethex: "#ffffff") 

thanks in advance.

xcode 8.2 • swift 3.0.2

extension uicolor {     convenience init?(hexstring: string) {         var chars = array(hexstring.hasprefix("#") ? hexstring.characters.dropfirst() : hexstring.characters)  // swift 4 use `var chars = array(hexstring.hasprefix("#") ? hexstring.dropfirst() : hexstring[...])`         let red, green, blue, alpha: cgfloat         switch chars.count {         case 3:             chars = chars.flatmap { [$0, $0] }             fallthrough         case 6:             chars = ["f","f"] + chars             fallthrough         case 8:             alpha = cgfloat(strtoul(string(chars[0...1]), nil, 16)) / 255             red   = cgfloat(strtoul(string(chars[2...3]), nil, 16)) / 255             green = cgfloat(strtoul(string(chars[4...5]), nil, 16)) / 255             blue  = cgfloat(strtoul(string(chars[6...7]), nil, 16)) / 255         default:             return nil         }         self.init(red: red, green: green, blue:  blue, alpha: alpha)     } } 

if let textcolor = uicolor(hexstring: "00f") {     print(textcolor) // r 0.0 g 0.0 b 1.0 1.0 }       uicolor(hexstring: "#00f")      // r 0.0 g 0.0 b 1.0 1.0 uicolor(hexstring: "#0000ff")   // r 0.0 g 0.0 b 1.0 1.0 uicolor(hexstring: "#ff0000ff") // r 0.0 g 0.0 b 1.0 1.0 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -