Reputation: 547
I have some custom colors for my application and now its saves like a dictionary, but I think this is no really good idea and I want to do extension for UIColor with a custom color.
That may look like this
var newColor = UIColor.MyColor // like UIColor.white
Maybe I should add to extension an enumeration with my colors?
Upvotes: 5
Views: 6176
Reputation: 12023
Using extension to extend the colors is a nice solution but if the app has multiple custom colors then it becomes repeatitive to write /255.0
for every color. We can add extension which takes RGB
values and converts to color.
extension UIColor {
/// color components value between 0 to 255
public convenience init(r: Int, g: Int, b: Int, alpha: CGFloat = 1.0) {
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
static let customRed: UIColor = UIColor(r: 255, g: 1, b: 1)
}
Another elegant solution would be to use enum to define different custom colors then add a property which will return the UIColor value using color extension defined above
enum ColorTheme {
case customRed
case customGreen
case customBlue
var color: UIColor {
switch self {
case .customRed:
return UIColor(r: 255, g: 1, b: 1)
case .customGreen:
return UIColor(r: 1, g: 255, b: 1)
case .customBlue:
return UIColor(r: 1, g: 1, b: 255)
}
}
}
then it can be used as
view.backgroundColor = ColorTheme.customRed.color
or if you use static color constants then
view.backgroundColor = UIColor.customRed
Upvotes: 6
Reputation: 15778
Create class property in UIColor extension
extension UIColor
{
class var themeColor:UIColor {
return UIColor(red: 210.0/255.0, green: 105.0/255.0, blue: 130.0/255.0, alpha: 1.0)
}
}
OR
extension UIColor {
static let themeColor = UIColor(red: 210.0/255.0, green: 105.0/255.0, blue: 130.0/255.0, alpha: 1.0)
}
Usage
self.view.backgroundColor = UIColor.themeColor
Upvotes: 23