我正在尝试设置Finder显示的彩色标签。我知道的唯一函数是setResourceValue。但这需要本地化的名称!
我能想象到我的母语和英语,但其他所有语言我都不知道。我无法相信这应该是正确的方法。
是否有翻译函数,它采用标准参数(如枚举或整数),并提供本地化的颜色名称?
我有一个运行部分,但只适用于两种语言(德语和英语):
let colorNamesEN = [ "None", "Gray", "Green", "Purple", "Blue", "Yellow", "Red", "Orange" ]
let colorNamesDE = [ "", "Grau", "Grün", "Lila", "Blau", "Gelb", "Rot", "Orange" ]
public enum TagColors : Int8 {
case None = -1, Gray, Green, Purple, Blue, Yellow, Red, Orange, Max
}
//let theURL : NSURL = NSURL.fileURLWithPath("/Users/dirk/Documents/MyLOG.txt")
extension NSURL {
// e.g. theURL.setColors(0b01010101)
func tagColorValue(tagcolor : TagColors) -> UInt16 {
return 1 << UInt16(tagcolor.rawValue)
}
func addTagColor(tagcolor : TagColors) -> Bool {
let bits : UInt16 = tagColorValue(tagcolor) | self.getTagColors()
return setTagColors(bits)
}
func remTagColor(tagcolor : TagColors) -> Bool {
let bits : UInt16 = ~tagColorValue(tagcolor) & self.getTagColors()
return setTagColors(bits)
}
func setColors(tagcolor : TagColors) -> Bool {
let bits : UInt16 = tagColorValue(tagcolor)
return setTagColors(bits)
}
func setTagColors(colorMask : UInt16) -> Bool {
// get string for all available and requested bits
let arr = colorBitsToStrings(colorMask & (tagColorValue(TagColors.Max)-1))
do {
try self.setResourceValue(arr, forKey: NSURLTagNamesKey)
return true
}
catch {
print("Could not write to file \(self.absoluteURL)")
return false
}
}
func getTagColors() -> UInt16 {
return getAllTagColors(self.absoluteURL)
}
}
// let initialBits: UInt8 = 0b00001111
func colorBitsToStrings(colorMask : UInt16) -> NSArray {
// translate bits to (localized!) color names
let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)!
// I don't know how to automate it for all languages possible!!!!
let colorNames = countryCode as! String == "de" ? colorNamesDE : colorNamesEN
var tagArray = [String]()
var bitNumber : Int = -1 // ignore first loop
for colorName in colorNames {
if bitNumber >= 0 {
if colorMask & UInt16(1<<bitNumber) > 0 {
tagArray.append(colorName)
}
}
bitNumber += 1
}
return tagArray
}
func getAllTagColors(file : NSURL) -> UInt16 {
var colorMask : UInt16 = 0
// translate (localized!) color names to bits
let countryCode = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)!
// I don't know how to automate it for all languages possible!!!!
let colorNames = countryCode as! String == "de" ? colorNamesDE : colorNamesEN
var bitNumber : Int = -1 // ignore first loop
var tags : AnyObject?
do {
try file.getResourceValue(&tags, forKey: NSURLTagNamesKey)
if tags != nil {
let tagArray = tags as! [String]
for colorName in colorNames {
if bitNumber >= 0 {
// color name listed?
if tagArray.filter( { $0 == colorName } ).count > 0 {
colorMask |= UInt16(1<<bitNumber)
}
}
bitNumber += 1
}
}
} catch {
// process the error here
}
return colorMask
}