使用不包含在 info.plist ios 中的自定义字体

Using custom font without including in info.plist ios

在 iOS 中,如果我们想使用自定义字体,我们必须在应用程序包中包含 font.ttf 并将 font.ttf 作为值添加到 [= 中的字体键22=]info.plist 文件.

我想使用一种自定义字体,其 ttf 文件将在应用程序安装到设备后从我的服务器下载。

1: 是否可以在我的应用程序中使用该字体

2:如果是,我该如何使用该字体?

NSData *inData = /* your decrypted font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef fontRef = CGFontCreateWithDataProvider(provider);

if (!CTFontManagerRegisterGraphicsFont(fontRef, &error)) {
    CFStringRef errorDescription = CFErrorCopyDescription(error);
    NSLog(@"Failed to load font: %@", errorDescription);
    CFRelease(errorDescription);
} else {
    CFStringRef fontNameRef = CGFontCopyPostScriptName(fontRef);
    UIFont *font = [UIFont fontWithName:(__bridge NSString *)fontNameRef size:someSize];
    // Your UIFont is ready.

    CFRelease(fontNameRef);
}
CFRelease(fontRef);
CFRelease(provider);

You can load a font this way at any time during your app’s execution, and it immediately becomes available in UIFont and UIWebView (via regular font-family CSS declarations, no @font-face required) just as if it had been declared in UIAppFonts.

Source

注意:您应该包括 CoreText 以使 CTFontManagerRegisterGraphicsFont 可用。