Extension for UIColor with custom colors it is real? [duplicate]

喜你入骨 提交于 2019-11-26 22:10:23

问题


This question already has an answer here:

  • How to access extension of UIColor in SWIFT? 8 answers
  • What is the best way to introduce a custom UIColor to a Swift project? [closed] 2 answers

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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/48805553/extension-for-uicolor-with-custom-colors-it-is-real

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!