简体   繁体   中英

Convert NSString color name to UIColor

I have a task to convert NSString color name ex:"Green" from configuration.plist file to a UIColor or a hex color code ex: "00ff00". I already have a code to convert hex color code to UIColor. I tried to use few another code sample for this task but is not working. Please help me out with a solution for this.

The only way this can be achieved is if you store hex color codes against color names in your app.

You can either maintain a property list or store these key value pairs in core data.

Your application would do something like this

Red:'Hex for red' Blue:'Hex for Blue' Green:'Hex for Green'

The manner in which you store these key value pairs is upto you. Now when you need to get a color from a color name, simply look up it's hex code and convert it into UIColor.

You would have to do this for all the colors that you expect in you application

If you are using swift you can easly develop that system. All start defining a set of possibile colors in an enum like this:

enum MyColor: String {
    case green
    case red
    case blue
    // and so on

    var hex: Int {
        switch self {
            case green: return 0xABCDF
            case red: return 0xABCDF
            case blue: return 0xABCDF
        }

    }
}

Then you need a new init for the UICOlor class that use this new enum

extension UIColor {

    convenience init(myColor: MyColor) {
        self.init(hex: myColor.raw)
    }

    init(hex: Int) {
    }
}

After that you can initilize yor colors like this:

let theColor = MyColor(rawValue: "green")
let color = UIcolor(myColor: theColor)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM