[ios] How can I use UIColorFromRGB in Swift?

In Objective-C, we use this code to set RGB color codes for views:

#define UIColorFromRGB(rgbValue)        
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

view.backgroundColor=UIColorFromRGB(0x209624);

How can I use this in Swift?

This question is related to ios swift

The answer is


I really liked Nate Cook's answer but I wanted something a little more idiomatic. I believe this is a really good use case for a convenience initializer via a custom extension.

// UIColorExtensions.swift
import Foundation
import UIKit

extension UIColor {
    convenience init(rgb: UInt) {
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

This can now be used like so:

view.backgroundColor = UIColor(rgb: 0x209624)

I would only recommend monkey patching UIKit classes like this in your own client code, not libraries.


You can use this:

//The color RGB #85CC4B
let newColor = UIColor(red: CGFloat(0x85)/255
                      ,green: CGFloat(0xCC)/255
                      ,blue: CGFloat(0x4B)/255
                      ,alpha: 1.0)

That can be simply done by using this initialization

view.backgroundColor = UIColor(hex: "067AB5")

I can see its already been answered but still hope one liner will help in better way.

import UIKit

let requiredColor = UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16)/255, 
                            green: CGFloat((rgbValue & 0x00FF00) >> 8)/255, 
                            blue: CGFloat(rgbValue & 0x0000FF)/255, alpha :1)

Updated: :Changes done as per example explained by Author of question to provide hex values


Nate Cook's answer is absolutely correct. Just for greater flexibility, I keep the following functions in my pack:

func getUIColorFromRGBThreeIntegers(red: Int, green: Int, blue: Int) -> UIColor {
    return UIColor(red: CGFloat(Float(red) / 255.0),
        green: CGFloat(Float(green) / 255.0),
        blue: CGFloat(Float(blue) / 255.0),
        alpha: CGFloat(1.0))
}

func getUIColorFromRGBHexValue(value: Int) -> UIColor {
    return getUIColorFromRGBThreeIntegers(red: (value & 0xFF0000) >> 16,
        green: (value & 0x00FF00) >> 8,
        blue: value & 0x0000FF)
}

func getUIColorFromRGBString(value: String) -> UIColor {
    let str = value.lowercased().replacingOccurrences(of: "#", with: "").
        replacingOccurrences(of: "0x", with: "");
        return getUIColorFromRGBHexValue(value: Int(str, radix: 16)!);
}

And this is how I use them:

// All three of them are identical:
let myColor1 = getUIColorFromRGBHexValue(value: 0xd5a637)
let myColor2 = getUIColorFromRGBString(value: "#D5A637")
let myColor3 = getUIColorFromRGBThreeIntegers(red: 213, green: 166, blue: 55)

Hope this will help. Everything is tested with Swift 3/Xcode 8.


For Xcode 9, use UIColor with RGB values.

shareBtn.backgroundColor = UIColor( red: CGFloat(92/255.0), green: CGFloat(203/255.0), blue: CGFloat(207/255.0), alpha: CGFloat(1.0) )

Preview:

button preview with custom RGB color

See additional Apple documentation on UIColor.


import Cocoa
class ViewController: NSViewController{
     override func viewDidLoad() {
            super.viewDidLoad()
    self.view.wantsLayer = true
    self.view.layer?.backgroundColor = NSColor(hexString: "#4d9b48").cgColor

}
extension NSColor {

            convenience init(hexString: String, alpha: CGFloat = 1.0) {
                  let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                  let scanner = Scanner(string: hexString)
                  if (hexString.hasPrefix("#")) {
                      scanner.scanLocation = 1
                  }
                  var color: UInt32 = 0
                  scanner.scanHexInt32(&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:alpha)
              }
              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 String(format:"#%06x", rgb)

            }
        }

I wanted to put

cell.backgroundColor = UIColor.colorWithRed(125/255.0, green: 125/255.0, blue: 125/255.0, alpha: 1.0)  

but that didn't work.

So I used:
For Swift

cell.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)  

So this is the workaround that I found.


I have used the following in swift.

let appRedColor = UIColor(red: 200.0/255.0, green: 16.0/255.0, blue: 46.0/255.0, alpha: 1.0)
let appSilverColor = UIColor(red: 236.0/255.0, green: 236.0/255.0, blue: 236.0/255.0, alpha: 1.0)
let appWhiteColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
let appNavyColor = UIColor(red: 19.0/255.0, green: 41.0/255.0, blue: 75.0/255.0, alpha: 1.0)

If you're starting from a string (not hex) this is a function that takes a hex string and returns a UIColor.
(You can enter hex strings with either format: #ffffff or ffffff)

Usage:

var color1 = hexStringToUIColor("#d3d3d3")

Swift 4:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

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

    if ((cString.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&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)
    )
}

Swift 3:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

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

    if ((cString.characters.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt32 = 0
    Scanner(string: cString).scanHexInt32(&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)
    )
}

Swift 2:

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString

    if (cString.hasPrefix("#")) {
      cString = cString.substringFromIndex(cString.startIndex.advancedBy(1))
    }

    if ((cString.characters.count) != 6) {
      return UIColor.grayColor()
    }

    var rgbValue:UInt32 = 0
    NSScanner(string: cString).scanHexInt(&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)
    )
}



Source: arshad/gist:de147c42d7b3063ef7bc


This is a nice extension for UIColor. You can use enum values(hex, string) and direct string values when you creating UIColor objects.

The extension we deserve https://github.com/ioramashvili/UsefulExtensions/blob/master/Extensions.playground/Pages/UIColor.xcplaygroundpage/Contents.swift


adding a swift 3 option:

cell.layer.borderColor = UIColor (red: 192.0/255.0, green: 192.0/255.0, blue: 197/255.0, alpha: 1.0).cgColor

This is worked for me in swift. Try this

bottomBorder.borderColor = UIColor (red: 255.0/255.0, green: 215.0/255.0, blue: 60/255.0, alpha: 1.0).CGColor

In Swift3, if you are starting with a color you have already chosen, you can get the RGB value online (http://imagecolorpicker.com) and use those values defined as a UIColor. This solution implements them as a background:

    @IBAction func blueBackground(_ sender: Any) {
        let blueColor = UIColor(red: CGFloat(160/255), green: CGFloat(183.0/255), blue: CGFloat(227.0/255), alpha: 1)
        view.backgroundColor = blueColor

@Vadym mentioned this above in the comments and it is important to define the CGFloat with a single decimal point


myLabel.backgroundColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0)

solution for argb format:

//  UIColorExtensions.swift
import UIKit
extension UIColor {

    convenience init(argb: UInt) {
        self.init(
            red: CGFloat((argb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((argb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(argb & 0x0000FF) / 255.0,
            alpha: CGFloat((argb & 0xFF000000) >> 24) / 255.0
        )
    }
}

usage:

var clearColor: UIColor = UIColor.init(argb: 0x00000000)
var redColor: UIColor = UIColor.init(argb: 0xFFFF0000)

You cannot use a complex macros like #define UIColorFromRGB(rgbValue) in swift. The replacement of simple macro in swift is global constants like

let FADE_ANIMATION_DURATION = 0.35

Still the complex macros that accept parameters are not supported by swift. you could use functions instead

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

Excerpt from Using swift with cocoa and objective C

Check @Nate Cooks answer for the Swift version of that function to be used here


UIColorFromRGB in Swift 4

button.layer.backgroundColor = UIColor(red: 112.0/255, green: 86.0/255, blue: 164.0/255, alpha: 1.0).cgColor

The simplest way to add color programmatically is by using ColorLiteral.

Just add the property ColorLiteral as shown in the example, Xcode will prompt you with a whole list of colors which you can choose. The advantage of doing so is lesser code, add HEX values or RGB. You will also get the recently used colors from the storyboard.

Example: self.view.backgroundColor = ColorLiteralenter image description here