从 iOS 13 开始,CTFontManager
具有以下功能:
@discussion Font assets are extracted from the asset catalog and registered. This call must be made after the completion handler of either NSBundleResourceRequest beginaccessingResourcesWithCompletionHandler: or conditionallyBeginaccessingResourcesWithCompletionHandler: is called successfully.
Name the assets using Postscript names for individual faces,or family names for variable/collection fonts. The same names can be used to unregister the fonts with CTFontManagerUnregisterFontDescriptors. In iOS,fonts registered with the persistent scope are not automatically available to other processes. Other process may call CTFontManagerRequestFonts to get access to these fonts.
@param fontAssetNames
Array of font name assets in asset catalog.
...
CTFontManagerRegisterFontsWithAssetNames(_ fontAssetNames: CFArray,_ bundle: CFBundle?,_ scope: CTFontManagerScope,_ enabled: Bool,_ registrationHandler: ((CFArray,Bool) -> Bool)?)
但是,Asset Catalog 没有任何方法可以添加“字体资产”。
我尝试过的:
- 采用字体
KanitRegular.ttf
(PostScript 名称为Kanit-Regular
)here。 - 在资产目录中创建了名为
Kanit-Regular
的数据资产。 - 将字体文件重命名为
Kanit-Regular.ttf
并将其放入数据资产中。
数据资产的 Contents.json
现在看起来像这样:
{
"data" : [
{
"filename" : "Kanit-Regular.ttf","idiom": "universal","universal-type-identifier" : "public.truetype-ttf-font"
}
],"info" : {
"author" : "xcode","version" : 1
}
}
- 尝试通过
CTFontManager
加载此字体
像这样:
func registerFont() {
var cfBundle: CFBundle?
if let bundle = Bundle(for: type(of: self)) {
cfBundle = CFBundleCreate(kCFAllocatorDefault,bundle.bundleURL as CFURL)
}
CTFontManagerRegisterFontsWithAssetNames(["Kanit-Regular"] as CFArray,cfBundle,.persistent,true) { (errors,done) -> Bool in
print(errors)
return done
}
}
此后,打印 errors
:
▿ 1 element
- 0 : Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument" UserInfo={CTFontManagerErrorFontAssetNameKey=(
"Kanit-Regular"
)}
有什么办法让它工作吗?