I give in, this is taking too long and I can't find the answer listed anywhere.
In the Framework Reference for UIColor there is a function initWithCGColor. How do you use this? Can someone please help with example? I am looking to initialize a color to a specific value!
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIColor_Class/index.html#//apple_ref/occ/instm/UIColor/initWithCGColor:
CGColorRef is a class used for drawing using Core graphics. If you want to initialise an UIColorobject with a specific RGB value, use
- initWithRed:green:blue:alpha:
Swift
let color = UIColor(red: 59/255.0, green: 136/255.0, blue: 195/255.0, alpha: 1)
Objective-C
UIColor * color = [UIColor colorWithRed:59/255.0f green:136/255.0f blue:195/255.0f alpha:1];
For helping purposes, I add some useful extension/macro for UIColor in order to initialise objects without having to consider the division by 255.
I am not the creator of this code but a grateful user who wants to share some time-saving code :
Swift
public extension UIColor{
class func initRGBA(r r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) -> UIColor
{
return UIColor(red:r/255, green: g/255, blue: b/255, alpha: a)
}
class func initRGB(r r:CGFloat, g:CGFloat, b:CGFloat) -> UIColor
{
return UIColor.initRGBA(r:r, g:g, b:b, a:1)
}
class func initRGBGRAY(gray:CGFloat) -> UIColor
{
return UIColor.initRGBA(r:gray, g:gray, b:gray, a:1)
}
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)
)
}
}
/// Let's initialize a color
let color = UIColor.initRGB(r: 24, g: 80, b: 145)
Objective-C
#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]
#define RGBGRAYCOLOR(g) [UIColor colorWithRed:(g)/255.0f green:(g)/255.0f blue:(g)/255.0f alpha:1]
/// Let's initialize a color
UIColor * color = RGBCOLOR(87, 99, 132);
Related
Every article up on the internet suggests me using RGB. But, I want to use Apple's green colour palette and I am futile in the venture. I know it's hashtag value but, unable to render it on the simulator due to the fact that I don't know the appropriate method to use it inside the view controller file.
Since, I have been able to render the desired colour by using Color Literal but, there is never an ending to learning. And, I want to know the coding way of it!
self.buttonStart.backgroundColor = UIColor(?)
? : What should I put inside the aforementioned parentheses to accomplish my task. Any suggestions?
You can try the following extension.
extension UIColor {
var applicationButtonColor : UIColor {
return UIColor(hex: "52C2FF")
}
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.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
)
}
}
And you can use it in your class like:
self.buttonStart.backgroundColor = UIColor().applicationButtonColor
You can instantiate a UIColor from a hex string value like following -
public extension UIColor {
static func from(hexString: String) -> UIColor {
var cleanString = hexString.replacingOccurrences(of: "#", with: "")
if cleanString.count == 3 {
var updatedString = ""
cleanString.forEach({ updatedString.append("\($0)\($0)") })
cleanString = updatedString
}
if cleanString.count == 6 {
cleanString = cleanString.appending("ff")
}
var baseValue: UInt32 = 0
Scanner(string: cleanString).scanHexInt32(&baseValue)
let red = CGFloat((baseValue >> 24) & 0xFF)/255.0
let green = CGFloat((baseValue >> 16) & 0xFF)/255.0
let blue = CGFloat((baseValue >> 8) & 0xFF)/255.0
let alpha = CGFloat((baseValue >> 0) & 0xFF)/255.0
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
Now from your code, you can call it like following -
self.buttonStart.backgroundColor = UIColor.from(hexString: "#AABBCC")
use this two public extensions in your code:
private extension Int {
func duplicate4bits() -> Int {
return (self << 4) + self
}
}
public extension UIColor {
convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
private convenience init?(hex3: Int, alpha: Float) {
self.init(red: CGFloat( ((hex3 & 0xF00) >> 8).duplicate4bits() ) / 255.0,
green: CGFloat( ((hex3 & 0x0F0) >> 4).duplicate4bits() ) / 255.0,
blue: CGFloat( ((hex3 & 0x00F) >> 0).duplicate4bits() ) / 255.0,
alpha: CGFloat(alpha))
}
private convenience init?(hex6: Int, alpha: Float) {
self.init(red: CGFloat( (hex6 & 0xFF0000) >> 16 ) / 255.0,
green: CGFloat( (hex6 & 0x00FF00) >> 8 ) / 255.0,
blue: CGFloat( (hex6 & 0x0000FF) >> 0 ) / 255.0, alpha: CGFloat(alpha))
}
private convenience init?(hex8: Int, alpha: Float) {
self.init(red: CGFloat( (hex8 & 0xFF000000) >> 24 ) / 255.0,
green: CGFloat( (hex8 & 0xFF0000) >> 16 ) / 255.0,
blue: CGFloat( (hex8 & 0xFF00) >> 8 ) / 255.0,
alpha: CGFloat((Int(alpha) & 0xFF) >> 0 ) / 255.0)
}
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = String(hex[hex.index(after: hex.startIndex)...])
}
guard let hexVal = Int(hex, radix: 16) else {
self.init()
return nil
}
switch hex.count {
case 3:
self.init(hex3: hexVal, alpha: alpha)
case 6:
self.init(hex6: hexVal, alpha: alpha)
case 8:
self.init(hex8: hexVal, alpha: alpha)
default:
self.init()
return nil
}
}
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
public convenience init?(hex: Int, alpha: Float) {
if (0x000000 ... 0xFFFFFF) ~= hex {
self.init(hex6: hex, alpha: alpha)
} else {
self.init()
return nil
}
}
}
Now from your code you can call it like here:
self.buttonStart.backgroundColor = UIColor.init(hexString: "#4d4d4d")
I am using the below code in my AppDelegate to set the colours for the Navigation Bar items. It works when I use the default colours (Step 1) and doesn't work when I use custom colours (Step 2).
Could someone please suggest how I could fix this ?
Step1: Works
// Set navigation bar, background color
UINavigationBar.appearance().barTintColor = UIColor.red
Step 2: Doesn't Work
// Set navigation bar, background color
UINavigationBar.appearance().barTintColor = UIColor(red: 41, green: 150, blue: 204, alpha: 1)
Here is my extension for my UIColor, implemented in one of my styles.swift file
extension UIColor {
convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
self.init(red: CGFloat(r/255), green: CGFloat(g/255), blue: CGFloat(b/255), alpha: CGFloat(a))
}
}
Try this
extension UIColor {
static func rgb( red : CGFloat, green : CGFloat, blue : CGFloat) -> UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
}
}
Step 2 :
UINavigationBar.appearance().barTintColor = UIColor.rgb(41,150,204)
You are using the default initialiser and not the one implemented in the extension :
Remove the params in your code like so :
UINavigationBar.appearance().barTintColor = UIColor(41, 150, 204,1)
UIColor's init takes CGFloat parameters, and CGFloat is a typedef for Double. Try to change your extension to accept Int as parameters instead of Double
You are not actually correctly using your extension.
To use it, call like this,
UINavigationBar.appearance().barTintColor = UIColor(41,150,204,1)
When you use underscore _ character for method names in the method definition, you have to omit method names when calling it.
Your extension is wrong. You have to divide by a float. As of now you are dividing by an Int so you are probably just getting 0 or 1.
It should be "r/255.0" etc...
EDIT: And as others have pointed out, you are not using your extension.
It should be
UIColor(41, 150, 204, 1)
On your UIColor Extension, do you have a need to define a convenience init? or can't you just use:
public func rgba(_ r:Int, _ g:Int, _ b:Int, _ a:CGFloat) -> UIColor {
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: a)
}
i want to change the color of tab bar background and i want to put my own color with color code, how to do that? I have the color code from sketch and dont know how to code that in swift.
In the viewController class for your tab bar put one of the following sections of code into your view did load depending on what values you have.
self.tabBar.barTintColor = UIColor.init(red: <#T##CGFloat#>, green: <#T##CGFloat#>, blue: <#T##CGFloat#>, alpha: <#T##CGFloat#>)
or
self.tabBar.barTintColor = UIColor.init(hue: <#T##CGFloat#>, saturation: <#T##CGFloat#>, brightness: <#T##CGFloat#>, alpha: <#T##CGFloat#>)
Try this code:
navigationController?.toolbar.barTintColor = UIColor.green // You can set to any colour.
You can specify in AppDelegate.swift how the appearance of your UITabBar will be:
UITabBar.appearance().barTintColor = .white
If you would like a method for custom colors using hex code, you can add an extension to UIColor like this:
extension UIColor {
convenience init (for hex: Int) {
let red: Int = (hex >> 16) & 0xff
let green: Int = (hex >> 8) & 0xff
let blue: Int = hex & 0xff
assert(
(red >= 0 && red <= 255) &&
(green >= 0 && green <= 255) &&
(blue >= 0 && blue <= 255),
"bad hex for UIColor"
)
self.init (red: CGFloat(red) / 255.0, green: CGFloat (green) / 255.0, blue: CGFloat (blue) / 255.0, alpha: 1.0)
}
// Create your own custom color from hex code
public class var customColor: UIColor {
return UIColor (for: 0x0067DF)
}
}
Then you can change your UITabBar background color to your own custom one:
UITabBar.appearance().barTintColor = .customColor
This question already has answers here:
How to use hex color values
(39 answers)
Closed 8 years ago.
I am trying to change the background color of TopScoreContainer to a lighter shade of green. I do not want to use greenColor() . Here is the line of code:
self.TopScoreContainer.backgroundColor = UIColor.greenColor()
Is it possible to substitute in a hexadecimal number or RGB value instead of greenColor() ? Thanks.
let myCustomColorHSBa = UIColor(hue: 120/360, saturation: 0.25 , brightness: 1.0 , alpha: 1)
let myCustomColorRGBa = UIColor(red: 191/255, green: 1, blue: 191/255, alpha: 1)
using it as an extension read-only computed var:
Read-Only Computed Properties
A computed property with a getter but no setter is known as a
read-only computed property. A read-only computed property always
returns a value, and can be accessed through dot syntax, but cannot be
set to a different value.
NOTE
You must declare computed properties—including read-only computed
properties—as variable properties with the var keyword, because their
value is not fixed. The let keyword is only used for constant
properties, to indicate that their values cannot be changed once they
are set as part of instance initialization.
You can simplify the declaration of a read-only computed property by
removing the get keyword and its braces:
extension UIColor {
var lightGreen: UIColor {
return UIColor(red: 191/255, green: 1, blue: 191/255, alpha: 1)
}
}
let lightGreen = UIColor().lightGreen
or you can also create your own htmlColor input as follow:
update: Xcode 7.2 • Swift 2.1.1
extension String {
subscript(range: Range<Int>) -> String {
return range.startIndex < 0 || range.endIndex > characters.count ? "Out of Range" : substringWithRange(Range(start: startIndex.advancedBy(range.startIndex),end: startIndex.advancedBy(range.endIndex)))
}
var hexaCGFloat: CGFloat {
return CGFloat(strtoul(self, nil, 16))
}
}
extension UIColor {
convenience init(htmlColor: String, alpha: Double) {
self.init(red: htmlColor[1...2].hexaCGFloat / 255.0, green: htmlColor[3...4].hexaCGFloat / 255.0, blue: htmlColor[5...6].hexaCGFloat / 255.0, alpha: CGFloat(alpha) )
}
convenience init(r: Int, g:Int , b:Int , a: Int) {
self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
}
}
let myColor = UIColor(r: 255 , g: 0, b: 0, a: 255)
let myHtmlWebColor = UIColor(htmlColor: "#bfffbf", alpha: 1.0)
This question already has answers here:
How to use hex color values
(39 answers)
Closed 8 years ago.
I am trying to change the background color of TopScoreContainer to a lighter shade of green. I do not want to use greenColor() . Here is the line of code:
self.TopScoreContainer.backgroundColor = UIColor.greenColor()
Is it possible to substitute in a hexadecimal number or RGB value instead of greenColor() ? Thanks.
let myCustomColorHSBa = UIColor(hue: 120/360, saturation: 0.25 , brightness: 1.0 , alpha: 1)
let myCustomColorRGBa = UIColor(red: 191/255, green: 1, blue: 191/255, alpha: 1)
using it as an extension read-only computed var:
Read-Only Computed Properties
A computed property with a getter but no setter is known as a
read-only computed property. A read-only computed property always
returns a value, and can be accessed through dot syntax, but cannot be
set to a different value.
NOTE
You must declare computed properties—including read-only computed
properties—as variable properties with the var keyword, because their
value is not fixed. The let keyword is only used for constant
properties, to indicate that their values cannot be changed once they
are set as part of instance initialization.
You can simplify the declaration of a read-only computed property by
removing the get keyword and its braces:
extension UIColor {
var lightGreen: UIColor {
return UIColor(red: 191/255, green: 1, blue: 191/255, alpha: 1)
}
}
let lightGreen = UIColor().lightGreen
or you can also create your own htmlColor input as follow:
update: Xcode 7.2 • Swift 2.1.1
extension String {
subscript(range: Range<Int>) -> String {
return range.startIndex < 0 || range.endIndex > characters.count ? "Out of Range" : substringWithRange(Range(start: startIndex.advancedBy(range.startIndex),end: startIndex.advancedBy(range.endIndex)))
}
var hexaCGFloat: CGFloat {
return CGFloat(strtoul(self, nil, 16))
}
}
extension UIColor {
convenience init(htmlColor: String, alpha: Double) {
self.init(red: htmlColor[1...2].hexaCGFloat / 255.0, green: htmlColor[3...4].hexaCGFloat / 255.0, blue: htmlColor[5...6].hexaCGFloat / 255.0, alpha: CGFloat(alpha) )
}
convenience init(r: Int, g:Int , b:Int , a: Int) {
self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
}
}
let myColor = UIColor(r: 255 , g: 0, b: 0, a: 255)
let myHtmlWebColor = UIColor(htmlColor: "#bfffbf", alpha: 1.0)