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
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")
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With