Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get color name in swift

Tags:

ios

swift

I am trying to get color name from UIButton in swift instead of value is there any way to do that. Thanks

I am using tintColor to set value as well to get value

    clickButton.tintColor = UIColor.blue

    var color = clickButton.tintColor

when I am printing color value I get (UIExtendedSRGBColorSpace 0 0 1 1) is there anyway I can get blue instead of value

like image 296
Punya Avatar asked Jun 21 '17 09:06

Punya


2 Answers

Add this extension to your project

extension UIColor {
    var name: String? {
        switch self {
        case UIColor.black: return "black"
        case UIColor.darkGray: return "darkGray"
        case UIColor.lightGray: return "lightGray"
        case UIColor.white: return "white"
        case UIColor.gray: return "gray"
        case UIColor.red: return "red"
        case UIColor.green: return "green"
        case UIColor.blue: return "blue"
        case UIColor.cyan: return "cyan"
        case UIColor.yellow: return "yellow"
        case UIColor.magenta: return "magenta"
        case UIColor.orange: return "orange"
        case UIColor.purple: return "purple"
        case UIColor.brown: return "brown"
        default: return nil
        }
    }
}

Now you can write

print(UIColor.red.name) // Optional("red")
like image 87
Luca Angeletti Avatar answered Sep 30 '22 16:09

Luca Angeletti


You cannot get the "human-readable" name of a UIColor by using a built-in. However you can get the RGB values, as described in this post.

If you really want to get the name of the color, you can build your own dictionary, as @BoilingFire pointed out in their answer:

var color = clickButton.tintColor!     // it is set to UIColor.blue
var colors = [UIColor.red:"red", UIColor.blue:"blue", UIColor.black:"black"]  // you should add more colors here, as many as you want to support.
var colorString = String()

if colors.keys.contains(color){
    colorString = colors[color]!
}

print(colorString)     // prints "blue"
like image 41
Mr. Xcoder Avatar answered Sep 30 '22 16:09

Mr. Xcoder