Swift 3:设置标签颜色

cbeh67ev  于 2023-11-16  发布在  Swift
关注(0)|答案(5)|浏览(127)

我正在尝试设置查找器显示的彩色标签。我知道的唯一函数是setResourceValue。但这需要本地化的名称!
我可以想象我的母语和英语,但其他的我都不知道。我不能相信,这应该是这样的。
are translation函数,它接受一个标准参数,如枚举或int,并提供本地化的颜色名称?
我有一个运行部分,但只有两种语言(德语和英语):

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
}

字符串

jaql4c8m

jaql4c8m1#

要设置单一颜色,setResourceValue API调用确实是你应该使用的。但是,你应该使用的资源键是NSURLLabelNumberKey,或者Swift 3中的URLResourceKey.labelNumberKey(不是NSURLTagNamesKey):

enum LabelNumber: Int {
    case none
    case grey
    case green
    case purple
    case blue
    case yellow
    case red
    case orange
}

do {
    // casting to NSURL here as the equivalent API in the URL value type appears borked:
    // setResourceValue(_, forKey:) is not available there, 
    // and setResourceValues(URLResourceValues) appears broken at least as of Xcode 8.1…
    // fix-it for setResourceValues(URLResourceValues) is saying to use [URLResourceKey: AnyObject], 
    // and the dictionary equivalent also gives an opposite compiler error. Looks like an SDK / compiler bug. 
    try (fileURL as NSURL).setResourceValue(LabelNumber.purple.rawValue, forKey: .labelNumberKey)
}
catch {
    print("Error when setting the label number: \(error)")
}

字符串
(This是an answer to a related Objective-C question的Swift 3端口。在Xcode 8.1,macOS Sierra 10.12.1下测试)
要设置多个颜色,您可以使用API来设置资源值和标签键。这两种编码之间的区别如下所述:http://arstechnica.com/apple/2013/10/os-x-10-9/9/-基本上标签键是在内部设置扩展属性“com.apple.metadata:_kMDItemUserTags”,它将这些标签字符串的数组存储为二进制plist,而上面显示的单色选项是设置32字节长的扩展属性值“com.apple.FinderInfo”的第10个字节。
该密钥名称中的“localized”有点令人困惑,因为实际上使用它设置的是用户在用户设置的标签名称中选择的标签集。这些标签值确实是本地化的,但仅限于根据最初创建帐户时的本地化设置进行设置的范围。为了演示,这些是我的系统上的JavaScript使用的标签值,我将其设置为芬兰本地化作为测试,并重新启动JavaScript,重新启动机器等:

➜  defaults read com.apple.Finder FavoriteTagNames
(
    "",
    Red,
    Orange,
    Yellow,
    Green,
    Blue,
    Purple,
    Gray
)


数据在二进制plist值中编码的方式只是最喜欢的标签名称,后面是数组中的索引(固定为长度8,实际值从1开始,即按照红色,橙子,黄色,绿色,蓝色,紫色,灰色的顺序匹配七种颜色)。例如:

xattr -p com.apple.metadata:_kMDItemUserTags foobar.png | xxd -r -p | plutil -convert xml1 - -o -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>Gray
1</string>
    <string>Purple
3</string>
    <string>Green
2</string>
    <string>Red
6</string>
</array>
</plist>


因此,系统本地化没有被考虑在内,事实上,用任何字符串后跟一个换行符,后跟一个1-7之间的数字来设置标签,将以标签索引所指示的颜色显示在屏幕上。以了解要应用的正确当前值,从而从收藏夹标签集合中获取要应用的标签(这样颜色和标签都匹配)您需要从URL偏好中读取该键(来自域'com.apple.xml'的键'FavoriteTagNames',它编码了如上所示的那些最喜欢的标签名称的数组)。
忽略上述复杂的情况下,你想得到标签名称 * 和 * 颜色正确,需要阅读从浏览器首选项域(这可能是你做不到的,取决于你的应用是否是沙盒),如果你想使用多种颜色,这里有一个直接使用扩展属性值设置颜色的示例解决方案(我使用SOExtendedAttributes来避免接触笨拙的xattr C API):

enum LabelNumber: Int {
    case none
    case gray
    case green
    case purple
    case blue
    case yellow
    case red
    case orange

    // using an enum here is really for illustrative purposes:
    // to know the correct values to apply you would need to read Finder preferences (see body of my response for more detail).
    var label:String? {
        switch self {
        case .none: return nil
        case .gray: return "Gray\n1"
        case .green: return "Green\n2"
        case .purple: return "Purple\n3"
        case .blue: return "Blue\n4"
        case .yellow: return "Yellow\n5"
        case .red: return "Red\n6"
        case .orange: return "Orange\n7"
        }
    }

    static func propertyListData(labels: [LabelNumber]) throws -> Data {
        let labelStrings = labels.flatMap { $0.label }
        let propData = try! PropertyListSerialization.data(fromPropertyList: labelStrings,
                                                           format: PropertyListSerialization.PropertyListFormat.binary,
                                                           options: 0)
        return propData
    }
}

do {
    try (fileURL as NSURL).setExtendedAttributeData(LabelNumber.propertyListData(labels: [.gray, .green]),
                                                     name: "com.apple.metadata:_kMDItemUserTags")
}
catch {
    print("Error when setting the label number: \(error)")
}

jvlzgdj9

jvlzgdj92#

由于新的URLResourceValues()结构体和标记号,我在不知道颜色名称的情况下就可以让它工作。
知道这些标记号中的每一个表示标记颜色:
0无
1灰
2绿色
3紫色
4个蓝色
5黄色
6红
7橙子
创建文件的URL:

var url = URL(fileURLWithPath: pathToYourFile)

字符串
它必须是一个var,因为我们要让它变异。
创建一个新的URLResourceValues示例(也需要是一个变量):

var rv = URLResourceValues()


像这样设置标签编号:

rv.labelNumber = 2 // green


最后,将标签写入文件:

do {
    try url.setResourceValues(rv)
} catch {
    print(error.localizedDescription)
}


在我们的示例中,我们将数字标记设置为2,因此现在该文件被标记为绿色。

shyt4zoc

shyt4zoc3#

历史

首先是我之前的答案,它适用于为文件设置 one 颜色标签:https://stackoverflow.com/a/39751001/2227743
然后@mz2发布了这个优秀的答案,它成功地将 * 几个 * 颜色标签设置到一个文件中,并解释了这个过程:https://stackoverflow.com/a/40314367/2227743
现在这个小插件,一个简单的后续@mz2的答案。

解决方案

我只是实现了@mz2的建议:我扩展了他的enum示例,使用方法获取用户的首选项,并在将属性设置到文件之前提取正确的本地化标签颜色名称。

enum LabelColors: Int {
    case none
    case gray
    case green
    case purple
    case blue
    case yellow
    case red
    case orange

    func label(using list: [String] = []) -> String? {
        if list.isEmpty || list.count < 7 {
            switch self {
            case .none: return nil
            case .gray: return "Gray\n1"
            case .green: return "Green\n2"
            case .purple: return "Purple\n3"
            case .blue: return "Blue\n4"
            case .yellow: return "Yellow\n5"
            case .red: return "Red\n6"
            case .orange: return "Orange\n7"
            }
        } else {
            switch self {
            case .none: return nil
            case .gray: return list[0]
            case .green: return list[1]
            case .purple: return list[2]
            case .blue: return list[3]
            case .yellow: return list[4]
            case .red: return list[5]
            case .orange: return list[6]
            }
        }
    }

    static func set(colors: [LabelColors],
                    to url: URL,
                    using list: [String] = []) throws
    {
        // 'setExtendedAttributeData' is part of https://github.com/billgarrison/SOExtendedAttributes
        try (url as NSURL).setExtendedAttributeData(propertyListData(labels: colors, using: list),
                                                    name: "com.apple.metadata:_kMDItemUserTags")
    }

    static func propertyListData(labels: [LabelColors],
                                 using list: [String] = []) throws -> Data
    {
        let labelStrings = labels.flatMap { $0.label(using: list) }
        return try PropertyListSerialization.data(fromPropertyList: labelStrings,
                                                  format: .binary,
                                                  options: 0)
    }

    static func localizedLabelNames() -> [String] {
        // this doesn't work if the app is Sandboxed:
        // the users would have to point to the file themselves with NSOpenPanel
        let url = URL(fileURLWithPath: "\(NSHomeDirectory())/Library/SyncedPreferences/com.apple.finder.plist")

        let keyPath = "values.FinderTagDict.value.FinderTags"
        if let d = try? Data(contentsOf: url) {
            if let plist = try? PropertyListSerialization.propertyList(from: d,
                                                                       options: [],
                                                                       format: nil),
                let pdict = plist as? NSDictionary,
                let ftags = pdict.value(forKeyPath: keyPath) as? [[AnyHashable: Any]]
            {
                var list = [(Int, String)]()
                // with '.count == 2' we ignore non-system labels
                for item in ftags where item.values.count == 2 {
                    if let name = item["n"] as? String,
                        let number = item["l"] as? Int {
                        list.append((number, name))
                    }
                }
                return list.sorted { $0.0 < $1.0 }.map { "\($0.1)\n\($0.0)" }
            }
        }
        return []
    }
}

字符串
使用方法:

do {
    // default English label names
    try LabelColors.set(colors: [.yellow, .red],
                        to: fileURL)

    // localized label names
    let list = LabelColors.localizedLabelNames()
    try LabelColors.set(colors: [.green, .blue],
                        to: fileURL,
                        using: list)
} catch {
    print("Error when setting label color(s): \(error)")
}

qv7cva1a

qv7cva1a5#

截至2023年11月,* 检索 * 多个彩色标签的最佳方法是这样的:

func getTags(for url: URL) -> [Tag] {
        let colors = NSWorkspace.shared.fileLabelColors
        do {
            //test($0)
            let tagsXattrName = "com.apple.metadata:_kMDItemUserTags"
            let tagsBinaryPropertyList = try url.extendedAttributeValue(forName: tagsXattrName)
            let tags:[String] = try PropertyListDecoder().decode([String].self, from: tagsBinaryPropertyList)
            return tags.map {
                let tagAndMaybeColor = $0.split(separator: "\n")
                if tagAndMaybeColor.count == 1 {
                    return Tag(name: $0, color: nil)
                }
                let colorIndex = Int(tagAndMaybeColor[1])!
                return Tag(name: String(tagAndMaybeColor[0]), color: colors[colorIndex])
            }
        } catch {
            //print("error gettings tags for \(url): \(error)")
            return []
        }
    }

字符串

相关问题