我想在 Cocoapod 中使用自定义字体,但在静态库中使用自定义字体时找不到任何内容。由于没有 info.plist 文件,因此无法告诉应用程序使用什么字体。
有任何想法吗?
有一种方法可以在不向 plist 文件中添加任何内容的情况下使用自定义字体。
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSURL *fontURL = [bundle URLForResource:<#fontName#> withExtension:@"otf"/*or TTF*/];
NSData *inData = [NSData dataWithContentsOfURL:fontURL];
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
CFStringRef errorDescription = CFErrorCopyDescription(error);
NSLog(@"Failed to load font: %@", errorDescription);
CFRelease(errorDescription);
}
CFSafeRelease(font);
CFSafeRelease(provider);
您还需要该CFSafeRelease
功能才能正常工作。
void CFSafeRelease(CFTypeRef cf) {
if (cf != NULL) {
CFRelease(cf);
}
}
来源:动态加载 iOS 字体。
斯威夫特等效:
extension UIFont {
static func registerFont(bundle: Bundle, fontName: String, fontExtension: String) -> Bool {
guard let fontURL = bundle.url(forResource: fontName, withExtension: fontExtension) else {
fatalError("Couldn't find font \(fontName)")
}
guard let fontDataProvider = CGDataProvider(url: fontURL as CFURL) else {
fatalError("Couldn't load data from the font \(fontName)")
}
guard let font = CGFont(fontDataProvider) else {
fatalError("Couldn't create font from data")
}
var error: Unmanaged<CFError>?
let success = CTFontManagerRegisterGraphicsFont(font, &error)
guard success else {
print("Error registering font: maybe it was already registered.")
return false
}
return true
}
}
如果我理解正确,您正在尝试为您的 Cocoapod 提供一种字体,并且您希望包含该 pod 的 iOS 应用程序能够使用您的自定义字体。
这个post_install
钩子似乎有效:
Pod::Spec.new do |s|
# ...
s.resources = "Resources/*.otf"
# ...
s.post_install do |library_representation|
require 'rexml/document'
library = library_representation.library
proj_path = library.user_project_path
proj = Xcodeproj::Project.new(proj_path)
target = proj.targets.first # good guess for simple projects
info_plists = target.build_configurations.inject([]) do |memo, item|
memo << item.build_settings['INFOPLIST_FILE']
end.uniq
info_plists = info_plists.map { |plist| File.join(File.dirname(proj_path), plist) }
resources = library.file_accessors.collect(&:resources).flatten
fonts = resources.find_all { |file| File.extname(file) == '.otf' || File.extname(file) == '.ttf' }
fonts = fonts.map { |f| File.basename(f) }
info_plists.each do |plist|
doc = REXML::Document.new(File.open(plist))
main_dict = doc.elements["plist"].elements["dict"]
app_fonts = main_dict.get_elements("key[text()='UIAppFonts']").first
if app_fonts.nil?
elem = REXML::Element.new 'key'
elem.text = 'UIAppFonts'
main_dict.add_element(elem)
font_array = REXML::Element.new 'array'
main_dict.add_element(font_array)
else
font_array = app_fonts.next_element
end
fonts.each do |font|
if font_array.get_elements("string[text()='#{font}']").empty?
font_elem = REXML::Element.new 'string'
font_elem.text = font
font_array.add_element(font_elem)
end
end
doc.write(File.open(plist, 'wb'))
end
end
钩子找到用户项目,并在第一个目标中(您可能可以通过要求 CocoaPods 给您真正的目标来完成此解决方案)它会查找其Info.plist
文件(通常只有一个)。最后,它查找UIAppFonts
文件的键,如果没有找到就创建它,如果字体名称不存在,则用字体名称填充数组。
对于那些在 2018+ 年发现这一点的人,我通过以下两个步骤获得了自定义字体以与界面构建器支持 (XCode 9) 一起使用:
将字体添加到框架的资源包中(在 .podspec 文件中)
s.resources = "PodName/**/*.{ttf}"
使用上面亚当的答案在运行时加载字体
#import <CoreText/CoreText.h>
void CFSafeRelease(CFTypeRef cf) { // redefine this
if (cf != NULL) {
CFRelease(cf);
}
}
+ (void) loadFonts {
NSBundle *frameworkBundle = [NSBundle bundleForClass:self.classForCoder];
NSURL *bundleURL = [[frameworkBundle resourceURL] URLByAppendingPathComponent:@"PodName.bundle"];
NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
NSURL *fontURL = [bundle URLForResource:@"HindMadurai-SemiBold" withExtension:@"ttf"];
NSData *inData = [NSData dataWithContentsOfURL:fontURL];
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
CFStringRef errorDescription = CFErrorCopyDescription(error);
NSLog(@"Failed to load font: %@", errorDescription);
CFRelease(errorDescription);
}
CFSafeRelease(font);
CFSafeRelease(provider);
}
运行 pod 安装
斯威夫特 5 实施
我可以通过在我的 Cocoapod 中创建以下类来解决这个问题,然后只需CustomFonts.loadAll()
从我的主应用程序的AppDelegate.swift
. 之后,我可以在我的应用程序中使用这样的字体:
let myFont = CustomFonts.Style.regular.font
请注意,Style
枚举不是必需的,它只是一种方便的分离关注点的方法。您也可以致电:
let myFont = UIFont(name: "SourceSansPro-SemiBold", size: 14)
import CoreText
public class CustomFonts: NSObject {
public enum Style: CaseIterable {
case mono
case regular
case semibold
public var value: String {
switch self {
case .mono: return "SourceCodePro-Medium"
case .regular: return "SourceSansPro-Regular"
case .semibold: return "SourceSansPro-SemiBold"
}
}
public var font: UIFont {
return UIFont(name: self.value, size: 14) ?? UIFont.init()
}
}
// Lazy var instead of method so it's only ever called once per app session.
public static var loadFonts: () -> Void = {
let fontNames = Style.allCases.map { $0.value }
for fontName in fontNames {
loadFont(withName: fontName)
}
return {}
}()
private static func loadFont(withName fontName: String) {
guard
let bundleURL = Bundle(for: self).url(forResource: "[CococpodName]", withExtension: "bundle"),
let bundle = Bundle(url: bundleURL),
let fontURL = bundle.url(forResource: fontName, withExtension: "ttf"),
let fontData = try? Data(contentsOf: fontURL) as CFData,
let provider = CGDataProvider(data: fontData),
let font = CGFont(provider) else {
return
}
CTFontManagerRegisterGraphicsFont(font, nil)
}
}
好吧,idk 是否可以作为答案,但您也可以查看需要字体的 cocoapod,如下所示: https ://github.com/parakeety/GoogleFontsiOS
库包含许多字体,我需要 Chivo,所以我添加了 pod 'GoogleFontsiOS/Chivo' 并使用它而不是自己编写字体加载代码。