448

I am trying to use hex color values in Swift, instead of the few standard ones that UIColor allows you to use, but I have no idea how to do it.

Example: how would I use #ffffff as a color?

3

42 Answers 42

1
2
0

Swift 2.0:

Make an extension of UIColor.

extension UIColor {
    convenience init(hexString:String) {
        let hexString:NSString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
        let scanner            = NSScanner(string: hexString as String)
        if (hexString.hasPrefix("#")) {
            scanner.scanLocation = 1
        }

        var color:UInt32 = 0
        scanner.scanHexInt(&color)

        let mask = 0x000000FF
        let r = Int(color >> 16) & mask
        let g = Int(color >> 8) & mask
        let b = Int(color) & mask

        let red   = CGFloat(r) / 255.0
        let green = CGFloat(g) / 255.0
        let blue  = CGFloat(b) / 255.0
        self.init(red:red, green:green, blue:blue, alpha:1)
    }

    func toHexString() -> String {
        var r:CGFloat = 0
        var g:CGFloat = 0
        var b:CGFloat = 0
        var a:CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
        return NSString(format:"#%06x", rgb) as String
    }

}

Usage:

//Hex to Color
    let countPartColor =  UIColor(hexString: "E43038")

//Color to Hex
let colorHexString =  UIColor(red: 228, green: 48, blue: 56, alpha: 1.0).toHexString()
1
  • 1
    Please avoid posting duplicate answers. If a question is a duplicate, flag it as such instead of answering. Thank you.
    – Eric Aya
    Apr 15, 2016 at 10:48
0

For swift 3

extension String {
    var hexColor: UIColor {        
        let hex = trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int = UInt32()       
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b: UInt32
        switch hex.characters.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            return .clear
        }
        return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }
}
0

You can use this extension on UIColor which converts Your String (Hexadecimal , RGBA) to UIColor and vice versa.

extension UIColor {

  //Convert RGBA String to UIColor object
  //"rgbaString" must be separated by space "0.5 0.6 0.7 1.0" 50% of Red 60% of Green 70% of Blue Alpha 100%
  public convenience init?(rgbaString : String){
      self.init(ciColor: CIColor(string: rgbaString))
  }

  //Convert UIColor to RGBA String
  func toRGBAString()-> String {
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    self.getRed(&r, green: &g, blue: &b, alpha: &a)
    return "\(r) \(g) \(b) \(a)"
  }

  //return UIColor from Hexadecimal Color string
  public convenience init?(hexString: String) {  
    let r, g, b, a: CGFloat

    if hexString.hasPrefix("#") {
      let start = hexString.index(hexString.startIndex, offsetBy: 1)
      let hexColor = hexString.substring(from: start)

      if hexColor.characters.count == 8 {
        let scanner = Scanner(string: hexColor)
        var hexNumber: UInt64 = 0

        if scanner.scanHexInt64(&hexNumber) {
          r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
          g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
          b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
          a = CGFloat(hexNumber & 0x000000ff) / 255
          self.init(red: r, green: g, blue: b, alpha: a)
          return
        }
      }
    }

    return nil
  }

  // Convert UIColor to Hexadecimal String
  func toHexString() -> String {
    var r: CGFloat = 0
    var g: CGFloat = 0
    var b: CGFloat = 0
    var a: CGFloat = 0
    self.getRed(&r, green: &g, blue: &b, alpha: &a)
    return String(
        format: "%02X%02X%02X",
        Int(r * 0xff),
        Int(g * 0xff),
        Int(b * 0xff))
  }
}
1
  • Alpha is not supported in toHexString()
    – Womble
    Apr 4, 2018 at 1:05
0

UIColor extension, This will greatly help you! (version:Swift 4.0)

import UIKit
extension UIColor {
/// rgb颜色
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
    self.init(red: r/255.0 ,green: g/255.0 ,blue: b/255.0 ,alpha:1.0)
}

/// 纯色(用于灰色)
convenience init(gray: CGFloat) {
    self.init(red: gray/255.0 ,green: gray/255.0 ,blue: gray/255.0 ,alpha:1.0)
}
/// 随机色
class func randomCGColor() -> UIColor {
    return UIColor(r: CGFloat(arc4random_uniform(256)), g: CGFloat(arc4random_uniform(256)), b: CGFloat(arc4random_uniform(256)))
}

/// hex颜色-Int
convenience init(hex:Int, alpha:CGFloat = 1.0) {
    self.init(
        red:   CGFloat((hex & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((hex & 0x00FF00) >> 8)  / 255.0,
        blue:  CGFloat((hex & 0x0000FF) >> 0)  / 255.0,
        alpha: alpha
    )
}
/// hex颜色-String
convenience init(hexString: String){
    var red:   CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue:  CGFloat = 0.0
    var alpha: CGFloat = 1.0
    let scanner = Scanner(string: hexString)
    var hexValue: CUnsignedLongLong = 0
    if scanner.scanHexInt64(&hexValue) {
        switch (hexString.characters.count) {
        case 3:
            red   = CGFloat((hexValue & 0xF00) >> 8)       / 15.0
            green = CGFloat((hexValue & 0x0F0) >> 4)       / 15.0
            blue  = CGFloat(hexValue & 0x00F)              / 15.0
        case 4:
            red   = CGFloat((hexValue & 0xF000) >> 12)     / 15.0
            green = CGFloat((hexValue & 0x0F00) >> 8)      / 15.0
            blue  = CGFloat((hexValue & 0x00F0) >> 4)      / 15.0
            alpha = CGFloat(hexValue & 0x000F)             / 15.0
        case 6:
            red   = CGFloat((hexValue & 0xFF0000) >> 16)   / 255.0
            green = CGFloat((hexValue & 0x00FF00) >> 8)    / 255.0
            blue  = CGFloat(hexValue & 0x0000FF)           / 255.0
        case 8:
            alpha = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
            red   = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
            green = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
            blue  = CGFloat(hexValue & 0x000000FF)         / 255.0
        default:
            log.info("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
        }
    } else {
        log.error("Scan hex error")
    }
    self.init(red:red, green:green, blue:blue, alpha:alpha)
}}
1
  • just a combination of the previous answers.
    – Sulthan
    Feb 23, 2018 at 10:58
0

RGBA Version Swift 3/4

I like @Luca's answer as i think it's the most elegant.

However I don't want my colours specified in ARGB. I'd rather RGBA + also i needed to hack in the case of dealing with strings that specify 1 character for each of the channels "#FFFA".

This version also adds error throwing + strips the '#' character if it's included in the string. Here is my modified form for Swift.

public enum ColourParsingError: Error
{
    
    case invalidInput(String)
}
extension UIColor {
    public convenience init(hexString: String) throws
    {
        let hexString = hexString.replacingOccurrences(of: "#", with: "")
        let hex = hexString.trimmingCharacters(in:NSCharacterSet.alphanumerics.inverted)
        var int = UInt32()
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b: UInt32
        switch hex.count 
        {
        case 3: // RGB (12-bit)
            (r, g, b,a) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17,255)
        //iCSS specification in the form of #F0FA
        case 4: // RGB (24-bit)
            (r, g, b,a) = ((int >> 12) * 17, (int >> 8 & 0xF) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF,255)
        case 8: // ARGB (32-bit)
            (r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            throw ColourParsingError.invalidInput("String is not a valid hex colour string: \(hexString)")
        }
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }
}
0

Try this

UIColor(hexString: "#ffffff")

.

extension UIColor {
  convenience init?(hexString hex: String) {
    var cString: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if cString.hasPrefix("#") {
      cString.remove(at: cString.startIndex)
    }

    guard cString.count == 6 else {
      return nil
    }

    var rgbValue: UInt64 = 0
    Scanner(string: cString).scanHexInt64(&rgbValue)

    self.init(
      red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
      green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
      blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
      alpha: CGFloat(1.0)
    )
  }
}
-1

Just some addiotion to the first answer

(haven't cehcked the alpha, may need to add an if netHext > 0xffffff):

extension UIColor {

struct COLORS_HEX {
    static let Primary = 0xffffff
    static let PrimaryDark = 0x000000
    static let Accent = 0xe89549
    static let AccentDark = 0xe27b2a
    static let TextWhiteSemiTransparent = 0x80ffffff
}

convenience init(red: Int, green: Int, blue: Int, alphaH: 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")
    assert(alphaH >= 0 && alphaH <= 255, "Invalid alpha component")

    self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alphaH) / 255.0)
}

convenience init(netHex:Int) {
    self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff, alphaH: (netHex >> 24) & 0xff)
}

}
-1

Swift 2.3: UIColor Extension. I Think its simpler.

extension UIColor {
    static func colorFromHex(hexString: String, alpha: CGFloat = 1) -> UIColor {
        //checking if hex has 7 characters or not including '#'
        if hexString.characters.count < 7 {
            return UIColor.whiteColor()
        }
        //string by removing hash
        let hexStringWithoutHash = hexString.substringFromIndex(hexString.startIndex.advancedBy(1))

        //I am extracting three parts of hex color Red (first 2 characters), Green (middle 2 characters), Blue (last two characters)
        let eachColor = [
            hexStringWithoutHash.substringWithRange(hexStringWithoutHash.startIndex...hexStringWithoutHash.startIndex.advancedBy(1)),
            hexStringWithoutHash.substringWithRange(hexStringWithoutHash.startIndex.advancedBy(2)...hexStringWithoutHash.startIndex.advancedBy(3)),
            hexStringWithoutHash.substringWithRange(hexStringWithoutHash.startIndex.advancedBy(4)...hexStringWithoutHash.startIndex.advancedBy(5))]

        let hexForEach = eachColor.map {CGFloat(Int($0, radix: 16) ?? 0)} //radix is base of numeric system you want to convert to, Hexadecimal has base 16

        //return the color by making color
        return UIColor(red: hexForEach[0] / 255, green: hexForEach[1] / 255, blue: hexForEach[2] / 255, alpha: alpha)
    }
}

Usage:

let color = UIColor.colorFromHex("#25ac09")
-1

I made a small function,placed it from where I can use it globally & working fine with swift 2.1:

func getColorFromHex(rgbValue:UInt32)->UIColor{
   let red = CGFloat((rgbValue & 0xFF0000) >> 16)/255.0
   let green = CGFloat((rgbValue & 0xFF00) >> 8)/255.0
   let blue = CGFloat(rgbValue & 0xFF)/255.0

   return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}

usage:

getColorFromHex(0xffffff)
1
  • 1
    You should be dividing by 255 not 256. There is no way to get white using your code. Only "almost white".
    – Sulthan
    Mar 26, 2017 at 10:15
-1

Swift 4.0

use this Single line of method

override func viewDidLoad() {
    super.viewDidLoad()

   let color = UIColor(hexColor: "FF00A0")
   self.view.backgroundColor = color

}

You have to create new Class or use any controller where u need to use Hex color. This extension class provide you UIColor that will convert Hex to RGB color.

extension UIColor {
convenience init(hexColor: String) {
    let scannHex = Scanner(string: hexColor)
    var rgbValue: UInt64 = 0
    scannHex.scanLocation = 0
    scannHex.scanHexInt64(&rgbValue)
    let r = (rgbValue & 0xff0000) >> 16
    let g = (rgbValue & 0xff00) >> 8
    let b = rgbValue & 0xff
    self.init(
        red: CGFloat(r) / 0xff,
        green: CGFloat(g) / 0xff,
        blue: CGFloat(b) / 0xff, alpha: 1
    )
  }
}
1
  • Again, that unnecessary usage of strings. Also, you are just copying the other answers.
    – Sulthan
    Mar 14, 2018 at 19:36
-2
extension UIColor {

      convenience init(hex: Int, alpha: Double = 1.0) {

      self.init(red: CGFloat((hex>>16)&0xFF)/255.0, green:CGFloat((hex>>8)&0xFF)/255.0, blue: CGFloat((hex)&0xFF)/255.0, alpha:  CGFloat(255 * alpha) / 255)
     }
}

Use this extension like:

let selectedColor = UIColor(hex: 0xFFFFFF)
let selectedColor = UIColor(hex: 0xFFFFFF, alpha: 0.5)
1
  • Utility classes are an antipattern in Swift. Swift has extensions.
    – Sulthan
    Mar 26, 2017 at 10:17
-2
extension UIColor {

    convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }

    convenience init(hex: Int, alpha: CGFloat = 1) {
        self.init(r: CGFloat((hex >> 16) & 0xff), g: CGFloat((hex >> 08) & 0xff), b: CGFloat((hex >> 00) & 0xff), a: alpha)
    }
}
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.