129

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?

1

22 Answers 22

183

Here's a Swift version of that function (for getting a UIColor representation of a UInt value):

func UIColorFromRGB(rgbValue: UInt) -> UIColor {
    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)
    )
}

view.backgroundColor = UIColorFromRGB(0x209624)
1
  • 1
    If you pass a defined color constant to this function do not forget to cast constant type to :UInt. e.g struct Color{ static let DarkBlue:UInt = 0x1f5e75 static let Blue:UInt = 0x3f7589 static let LightBlue:UInt = 0x7fa3b0 } Dec 28, 2015 at 7:25
135

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.

3
  • 36
    let color: UIColor = UIColor( red: CGFloat(0/255.0), green: CGFloat(110/255.0), blue: CGFloat(255/255.0), alpha: CGFloat(1.0) )
    – Vadym
    Sep 28, 2014 at 10:08
  • 1
    The original would've worked if you put it in parenthesis (like the second), and put the first numbers in front of the "/" sign as a decimal number so it does not truncate to an integer. Jan 1, 2018 at 21:43
  • this is what worked for me , specificly the swift part
    – Taoufik
    Jun 14, 2022 at 13:10
67

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.

3
  • Where do I get the rgb value 0x209624? Mar 5, 2018 at 12:57
  • @ConsBulaquena it's just 0x followed by any hex color - color-hex.com Mar 7, 2018 at 16:59
  • I see. Very useful! Thanks @bloudermilk Mar 9, 2018 at 21:37
48
myLabel.backgroundColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0)
0
40

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

3
  • 6
    this is Amazing ! Apr 13, 2018 at 6:20
  • 1
    thanks for sharing this quick hand.. new learning.. :)
    – Ameer
    Aug 6, 2020 at 14:37
  • It is good for quick proto, but if you need to change some colors a bit after a while, and there are tens of places, you are in trouble.
    – Dren
    Feb 22 at 15:23
35

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

15

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.

11

UIColorFromRGB in Swift 4

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

https://uiwjs.github.io/ui-color/

SwiftUI

Color(red: 1.33, green: 0.56, blue: 0.56).opacity(0.61)

Swift for iOS

UIColor(red: 1.33, green: 0.56, blue: 0.56, alpha: 0.61)

Swift for macOS

NSColor(red: 1.33, green: 0.56, blue: 0.56, alpha: 0.61)

Objective-C for iOS

[UIColor colorWithRed: 1.33 green: 0.56 blue: 0.56 alpha: 0.61];

Objective-C for macOS

[NSColor colorWithCalibratedRed: 1.33 green: 0.56 blue: 0.56 alpha: 0.61];

enter image description here

4

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)
1
  • I have used the following in swift: let isItAnswer = false; Mar 28, 2017 at 18:56
4

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)
3

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)
3

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
0
3

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
2

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

0
1

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.

0
1

Swift 5 ++

simply use this extension

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

Use

 // Example 1
 let color = UIColor(r: 255.0, g: 152.0, b: 56.0)

 // Example 2
 let color2 = UIColor(r: 255.0, g: 152.0, b: 56.0,a: 1.0)
0

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

1
  • Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.
    – Tobi Nary
    Mar 2, 2016 at 8:14
0

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

0
0

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

-1
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)

            }
        }
-1

I'm using:

 extension UIColor {
        static func rgba(_ red: Int, _ green: Int, _ blue: Int, _ alpha: Double) -> UIColor {
            assert(red >= 0 && red <= 255, "Invalid red component")
            assert(green >= 0 && green <= 255, "Invalid green component")
            assert(blue >= 0 && blue <= 255, "Invalid blue component")
    
            return self.init(red: CGFloat(red) / 255.0,
                             green: CGFloat(green) / 255.0,
                             blue: CGFloat(blue) / 255.0,
                             alpha: alpha)
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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