Akrastan
Akrastan

Reputation: 13

How to convert standard color names in string to UIColor values

I have a variable:

var colorName = String()

I need the tint color of a button to be the appropriate color. Doing the following:

cell.btn.tintColor = UIColor.red 

works for me. But I need to use my colorName variable instead of "UIColor.red" expression.

How would I initialize a UIColor with the string red to be UIColor.red?

Upvotes: 1

Views: 1468

Answers (2)

Apps Maven
Apps Maven

Reputation: 1420

As there is no pre-defined method to do this so we need to create a custom method for this, so you can use the method defined below:-

func chooseColor(_ name: String) -> UIColor{
    switch name {
    case "red":
        return UIColor.red //or you can use hex colors here
    case "blue":
        return UIColor.blue
    case "brown":
        return UIColor.brown
    case "green":
        return UIColor.green
    case "yellow":
        return UIColor.yellow
    default :
        return UIColor.black
    }
    
}

Then, you can access it by calling it like called in the statement below:-

 cell.btn.tintColor = chooseColor("red")

Upvotes: 0

Wyetro
Wyetro

Reputation: 8588

There is no built in feature to make a UIColor with a name. You can write an extension like the one by Paul Hudson found here: https://www.hackingwithswift.com/example-code/uicolor/how-to-convert-a-html-name-string-into-a-uicolor

Simplified example:

extension UIColor {
    public func named(_ name: String) -> UIColor? {
        let allColors: [String: UIColor] = [
            "red": .red,
        ]
        let cleanedName = name.replacingOccurrences(of: " ", with: "").lowercased()
        return allColors[cleanedName]
    }
}

And then use it:

let redColor = UIColor().named("red")

You could also define an xcassets like in this article: https://medium.com/bobo-shone/how-to-use-named-color-in-xcode-9-d7149d270a16

And then use UIColor(named: "red")

Upvotes: 1

Related Questions