是否可以在swift中获取颜色名称

时间:2017-06-21 09:48:02

标签: ios swift

我试图从swift中获取UIButton的颜色名称而不是值,有没有办法做到这一点。感谢

我正在使用tintColor设置值以获取值

    clickButton.tintColor = UIColor.blue

    var color = clickButton.tintColor

当我打印颜色值时,我得到(UIExtendedSRGBColorSpace 0 0 1 1)无论如何我可以得到蓝色而不是值

5 个答案:

答案 0 :(得分:5)

将此扩展程序添加到您的项目中

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
        }
    }
}

现在你可以写

print(UIColor.red.name) // Optional("red")

答案 1 :(得分:3)

使用内置功能无法获得UIColor的“人类可读”名称。但是,您可以按this post

中的说明获取RGB

如果您真的想获得颜色的名称,可以建立自己的字典,如@BoilingFire在答案中指出的那样:

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"

答案 2 :(得分:1)

我认为不可能,但您可以构建自己的词典并搜索与该颜色对象对应的键。 不管怎样,任何颜色都没有名字。

var colors = ["blue": UIColor.blue, ...]

答案 3 :(得分:1)

您可以使用此扩展名来获取通过XCode中的Color Assets创建的颜色的名称。

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)
    }
}

结果:

enter image description here

答案 4 :(得分:0)

从 iOS 14.0+ 开始,您还可以使用 https://developer.apple.com/documentation/uikit/uicolor/3600314-accessibilityname

UIColor.systemRed.accessibilityName // returns "Red"
相关问题