2017-06-21 84 views
2

我想從swift中獲取顏色名稱而不是值,有沒有辦法做到這一點。由於是否有可能在swift中獲取顏色名稱

我使用tintColor設定值以及獲取值

clickButton.tintColor = UIColor.blue 

    var color = clickButton.tintColor 

當我打印的顏色值,我得到(UIExtendedSRGBColorSpace 0 0 1 1)有反正我能得到藍色的,而不是價值

+0

不,你不能得到的UIColor的名稱,RGB值可以得到。並沒有使用顏色名稱 –

回答

1

通過使用內置函數,您無法獲得UIColor的「人類可讀」名稱。但是,您可以獲得RGB值,如this post中所述。

如果你真的想要得到的顏色的名稱,你可以建立自己的字典,如@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" 
+1

很好的答案,這會幫助你。 –

1

我不認爲這是可能的,但你可以建立你自己的詞典並搜索與該顏色對象相對應的鍵。 反正任何顏色都不會有名字。

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

這個擴展添加到您的項目

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") 
相關問題