我正在考虑添加一个按用户定义的字体集合对可用字体进行排序的选项(我希望 Pages 和 Keynote 能做到这一点!),但看起来访问这些集合的旧方法在 10.11 中已被弃用:
是否有一种新的方式来访问和使用这些字体集合?
最佳答案
我最近一直在研究字体集合,因此我可能可以为您提供一些信息。
NSFontCollection
API 有点奇怪。它提供对“命名字体集合”的访问,但与所述集合关联的名称不附加到它们。如果这没有意义,那是因为它没有意义。不过,让我尝试将其分解:
要添加系统范围字体集合:
// Create a font descriptor (or descriptors) with whatever attributes you want
let descriptor = NSFontDescriptor(fontAttributes: nil)
// Create a font collection with the above descriptor(s)
let collection = NSFontCollection(descriptors: [descriptor])
// In Objective-C, the `+ showFontCollection:withName:visibility:error:`
// method returns `YES` if the collection was shown or `NO` if an error occurred.
// The error is passed via pointer supplied to the `error:` parameter.
//
// In Swift, the method returns `()` (aka nil literal), and instead of passing
// the error in a pointer, it `throws`, so you have to wrap the call in a `do`
// statement and catch the error (or suppress error propagation via `try!`):
do {
try NSFontCollection.showFontCollection(collection: NSFontCollection,
withName: "Visible to All Users", visibility: .Computer)
}
catch {
print("There was an error showing font collection. Info: \(error)")
}
要添加用户可见字体集合:
重复上述步骤,将 .Computer
替换为 .User
:
do {
try NSFontCollection.showFontCollection(collection: NSFontCollection,
withName: "Visible to the Current User", visibility: .User)
}
catch {
print("There was an error showing font collection. Info: \(error)")
}
要添加非持久字体集合:
重复上述步骤,将 .Computer
替换为 .Process
:
do {
try NSFontCollection.showFontCollection(collection: NSFontCollection,
withName: "Visible for Current Process", visibility: .Process)
}
catch {
print("There was an error showing font collection. Info: \(error)")
}
后续步骤...
一旦你有了一个集合,你就可以使用NSMutableFontCollection
类来改变它。继续上面的示例,您将执行以下操作:
let mutableCollection = collection.mutableCopy() as! NSMutableFontCollection
let boldTrait = [NSFontWeightTrait: NSFontWeightBold]
let boldAttributes = [NSFontTraitsAttribute: boldTrait]
let boldDescriptor = NSFontDescriptor(fontAttributes: newAttributes)
mutableCollection.addQueryForDescriptors([boldDescriptor])
此时,API 再次变得奇怪。我们已将描述符添加到“命名集合”中,但在您再次“显示”字体集合之前,UI 中不会显示任何内容。换句话说,进行任何更改后,您必须再次调用 showFontCollection(_:withName:visibility:)
。
同样,如果您想移除/删除集合,则必须调用 hideFontCollectionWithName(_:visibility:)
。尽管其名称无伤大雅,但此方法会从磁盘中完全删除持久集合,因此请小心。
下一步后续步骤...
在应用程序的后续启动中,您可以使用 NSFontCollection(name:visibility:)
方法检索任何持久性集合,如下所示:
// Retrieve collection created at an earlier time
let collectionOnDisk = NSFontCollection(name: "Visible to All Users", visibility: .Computer)
我想我已经涵盖了大部分内容,但如果我遗漏了某些内容,或者您有疑问,请告诉我。祝你好运!
关于cocoa - 是否有未弃用的方法来访问 OS X 10.11 的字体集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31971169/