Search code examples
swiftstringtype-conversionuicolor

How to Convert a string into a UIColor (Swift)


I have several colors defined in my SKScene:

let color1 = UIColor(red: 1, green: 153/255, blue: 0, alpha: 1)
let color2 = UIColor(red: 74/255, green: 134/255, blue: 232/255, alpha: 1)
let color3 = UIColor(red: 0, green: 0, blue: 1, alpha: 1)
let color4 = UIColor(red: 0, green: 1, blue: 0, alpha: 1)
let color5 = UIColor(red: 153/255, green: 0, blue: 1, alpha: 1)
let color6 = UIColor(red: 1, green: 0, blue: 0 , alpha: 1)

These colors correspond to tiles with different values in my game. The one tile goes with color1 and so on...

When the tiles are added together, I add their values and want to give them a new color according to their value.

So I want the value of the tile to play an effect on what color the tile is.

I have tried:

tile.color = UIColor(named: "color\(value)") ?? color1

But when I do this, it always uses the default value(color1).

How do I make so the value of the tile plays an effect in the color of the tile?


Solution

  • UIColor named: only works when you define a color set asset. Since your colors are defined in code, UIColor named: will never return anything but nil.

    One solution is to put your colors into a dictionary instead of separate variables.

    let colors: [String: UIColor] = [
        "color1" : UIColor(red: 1, green: 153/255, blue: 0, alpha: 1),
        "color2" : UIColor(red: 74/255, green: 134/255, blue: 232/255, alpha: 1),
        "color3" : UIColor(red: 0, green: 0, blue: 1, alpha: 1),
        "color4" : UIColor(red: 0, green: 1, blue: 0, alpha: 1),
        "color5" : UIColor(red: 153/255, green: 0, blue: 1, alpha: 1),
        "color6" : UIColor(red: 1, green: 0, blue: 0 , alpha: 1),
    ]
    

    Then you can get your color as:

    tile.color = colors["color\(value)"] ?? colors["color1"]!