Search code examples
iosswiftuicolor

Swift string as UIColor object


I am trying to convert the string 'red' to UIColor.red, this is what I got so far:

let rowColor = row.ResponsibilityColor!

print(rowColor) //this is "red"

styleToApply.backgroundColor = UIColor.yellow

Now if I know if I do this, I will no doubt have an error as UIColor does not have a property called rowColor:

styleToApply.backgroundColor = UIColor.rowColor

Is it possible to accomplish what I am trying to do? I dont have to use if conditions, because the color values are coming from a web service.


Solution

  • Do you want something like that ?

    extension String {
        func color() -> UIColor? {
            switch(self){
            case "red":
                return UIColor.red
            default:
                return nil
            }
        }
    }
    

    Use it like that :

    let rowColor = "red"
    let color = rowColor.color()
    print(color ?? "color not found in String extensions.")
    

    it prints the red UIColor : r 1,0 g 0,0 b 0,0 a 1,0

    The inconvenient is that you must have all your API color identifiers declared in the String extension to convert it to the right UIColor, this solution can be improved.