我试图迅速从UIButton获取颜色名称而不是值,有没有办法做到这一点。谢谢
我正在使用tintColor设置值以获取价值
clickButton.tintColor = UIColor.blue
var color = clickButton.tintColor
Run Code Online (Sandbox Code Playgroud)
当我打印颜色值时,我得到的是(UIExtendedSRGBColorSpace 0 0 1 1)是否可以得到蓝色而不是值
小智 6
从 iOS 14.0+ 开始,您还可以使用https://developer.apple.com/documentation/uikit/uicolor/3600314-accessibilityname
UIColor.systemRed.accessibilityName // returns "Red"
Run Code Online (Sandbox Code Playgroud)
您无法UIColor通过使用内置来获得 a 的“人类可读”名称。然而,你可以得到的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"
Run Code Online (Sandbox Code Playgroud)
将此扩展添加到您的项目中
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以写
print(UIColor.red.name) // Optional("red")
Run Code Online (Sandbox Code Playgroud)
您可以使用此扩展来获取通过 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)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
| 归档时间: |
|
| 查看次数: |
3599 次 |
| 最近记录: |