Can I embed a custom font in a bundle and access it from an ios framework?
Swift 3:
Firstly, don't access framework bundle from main with appending path components... Instantiate it from its identifier. You can get font URLs like this:
static func fontsURLs() -> [URL] {
let bundle = Bundle(identifier: "com.company.project.framework")!
let fileNames = ["Roboto-Bold", "Roboto-Italic", "Roboto-Regular"]
return fileNames.map({ bundle.url(forResource: $0, withExtension: "ttf")! })
}
And I find it nice to have UIFont
extension for registering fonts:
public extension UIFont {
public static func register(from url: URL) throws {
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
throw SVError.internal("Could not create font data provider for \(url).")
}
let font = CGFont(fontDataProvider)
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font, &error) else {
throw error!.takeUnretainedValue()
}
}
}
Now enjoy the registration:
do {
try fontsURLs().forEach({ try UIFont.register(from: $0) })
} catch {
print(error)
}
This is a new method that lets you load fonts dynamically without putting them in your Info.plist: http://www.marco.org/2012/12/21/ios-dynamic-font-loading