10

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

Punya
  • 353
  • 1
  • 3
  • 12

8 Answers8

13

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")
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
6

From iOS 14.0+ you can also use https://developer.apple.com/documentation/uikit/uicolor/3600314-accessibilityname

UIColor.systemRed.accessibilityName // returns "Red"
5

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"
Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
5

You can use this extension to get name of color created via Color Assets in XCode.

extension UIColor {
    /// Name of color. Only colors created with XCode Color Assets will return actual name, colors created programatically will always return nil.
    var name: String? {
        let str = String(describing: self).dropLast()
        guard let nameRange = str.range(of: "name = ") else {
            return nil
        }
        let cropped = str[nameRange.upperBound ..< str.endIndex]
        if cropped.isEmpty {
            return nil
        }
        return String(cropped)
    }
}

Result:

enter image description here

Adam
  • 1,776
  • 1
  • 17
  • 28
2

Swift 5 and above iOS14

Create an extension for UIColor

extension UIColor {

convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: CGFloat(r/255), green: CGFloat(g/255), blue: CGFloat(b/255), alpha: CGFloat(a))
}

convenience init(hex: String) {
    let scanner = Scanner(string: hex)
    scanner.scanLocation = 0
    
    var rgbValue: UInt64 = 0
    
    scanner.scanHexInt64(&rgbValue)
    
    let r = (rgbValue & 0xff0000) >> 16
    let g = (rgbValue & 0xff00) >> 8
    let b = rgbValue & 0xff
    
    self.init(
        red: CGFloat(r) / 0xff,
        green: CGFloat(g) / 0xff,
        blue: CGFloat(b) / 0xff, alpha: 1
    )
}

func getRGBAComponents() -> (red: Int, green: Int, blue: Int, alpha: Int)?
{
    var fRed : CGFloat = 0
    var fGreen : CGFloat = 0
    var fBlue : CGFloat = 0
    var fAlpha: CGFloat = 0
    if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
        let iRed = Int(fRed * 255.0)
        let iGreen = Int(fGreen * 255.0)
        let iBlue = Int(fBlue * 255.0)
        let iAlpha = 1
        
        return (red:iRed, green:iGreen, blue:iBlue, alpha:iAlpha)
    } else {
        // Could not extract RGBA components:
        return nil
    }
}

class func colorWithRGB(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1.0) -> UIColor {
    return UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: alpha)
}

convenience init(red: Int, green: Int, blue: Int) {
       assert(red >= 0 && red <= 255, "Invalid red component")
       assert(green >= 0 && green <= 255, "Invalid green component")
       assert(blue >= 0 && blue <= 255, "Invalid blue component")

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
   }

   convenience init(rgb: Int) {
       self.init(
           red: (rgb >> 16) & 0xFF,
           green: (rgb >> 8) & 0xFF,
           blue: rgb & 0xFF
       )
   }

}

Use like below Code

     let RGBArray =  YOUR_RGB_COLOR?.components(separatedBy: ",")
        let _color = UIColor(red:Int(RGBArray?[0] ?? "0") ?? 255 , green: Int(RGBArray?[1] ?? "0") ?? 255, blue: Int(RGBArray?[2] ?? "0") ?? 255)
        if #available(iOS 14.0, *) {
            let mString  = _color.accessibilityName
            print(mString)
        }

OUTPUT:

Red

Priyank Patel
  • 791
  • 8
  • 6
1

I don't think it's possible but you could build your own dictionnary and search for the key that corresponds to that color object. Not any color would have a name anyways.

var colors = ["blue": UIColor.blue, ...]
BoilingFire
  • 191
  • 1
  • 9
0

Swift 5.5

Let's assume you have a variable Orange of type UIColor.

var orange: UIColor = UIColor(displayP3Red: 1, green: 0.5, blue: 0, alpha: 1)

You can get the color name by:

var colorName: String {
    orange.accessibilityName
}

Hope this helped. Cheers

Usefz89
  • 53
  • 5
0

An extencion for class Color in SwiftUI can be :

extension Color {
    var name: String? {
        let description = self.description
        let firstOccurenceIndex = description.firstIndex(of: "\"") ?? description.startIndex
        let startIndex = description.index(firstOccurenceIndex, offsetBy: 1)
        let suffix = description.suffix(from: startIndex)
        let lastOccurenceIndex = suffix.firstIndex(of: "\"") ?? description.endIndex
        let name = suffix.prefix(upTo: lastOccurenceIndex)
        return String(name)
    }
}
Edu
  • 5
  • 3