This question already has an answer here:
-
How to use hex color values
32 answers
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)