How can I use UIColorFromRGB in Swift?
IosSwiftIos Problem Overview
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?
Ios Solutions
Solution 1 - Ios
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)
Solution 2 - Ios
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.
Solution 3 - Ios
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.
Solution 4 - Ios
myLabel.backgroundColor = UIColor(red: 50.0/255, green: 150.0/255, blue: 65.0/255, alpha: 1.0)
Solution 5 - Ios
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.
Solution 6 - Ios
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
Solution 7 - Ios
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:
See additional Apple documentation on UIColor.
Solution 8 - Ios
UIColorFromRGB in Swift 4
button.layer.backgroundColor = UIColor(red: 112.0/255, green: 86.0/255, blue: 164.0/255, alpha: 1.0).cgColor
Solution 9 - Ios
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)
Solution 10 - Ios
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)
Solution 11 - Ios
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
Solution 12 - Ios
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
Solution 13 - Ios
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];
Solution 14 - Ios
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
Solution 15 - Ios
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)
Solution 16 - Ios
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)
Solution 17 - Ios
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.
Solution 18 - Ios
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
Solution 19 - Ios
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
Solution 20 - Ios
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
Solution 21 - Ios
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)
}
}
Solution 22 - Ios
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)
}
}