Search code examples
iosswiftstringcolorsuicolor

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?


Solution

  • 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")