Skip to content

Instantly share code, notes, and snippets.

@matnogaj
Created January 25, 2017 15:35
Show Gist options
  • Save matnogaj/1de09672b26ad51f899d6c9a24459ea3 to your computer and use it in GitHub Desktop.
Save matnogaj/1de09672b26ad51f899d6c9a24459ea3 to your computer and use it in GitHub Desktop.
Register fonts from files. Useful especially for fonts in frameworks.
public class FontsUtility {
/**
Call this at the app startup to register custom fonts and use them in the app.
*/
public static func registerFonts() {
let bundle = Bundle(for: FontsUtility.self)
guard let path = bundle.path(forResource: "Info", ofType: "plist") else {
print("[RegisterFonts] Failed to find Info.plist")
return
}
guard let infoDict = NSDictionary(contentsOfFile: path) else {
print("[RegisterFonts] Failed to load Info.plist")
return
}
guard let fontsArray = infoDict["UIAppFonts"] as? Array<String> else {
print("[RegisterFonts] Failed to load custom fonts array")
return
}
fontsArray.forEach { registerFont(fontName: $0, bundle: bundle) }
}
static func registerFont(fontName: String, bundle: Bundle) {
guard let fontPath = bundle.path(forResource: fontName, ofType: nil) else {
print("[RegisterFont] Failed to get path for \(fontName)")
return
}
let fontURL = URL(fileURLWithPath: fontPath)
guard let fontData = try? Data(contentsOf: fontURL) else {
print("[RegisterFont] Failed to load \(fontName) data")
return
}
guard let provider = CGDataProvider(data: fontData as CFData) else {
print("[RegisterFont] Failed to create data provider for \(fontName) data")
return
}
let font = CGFont(provider)
var error: Unmanaged<CFError>? = nil
let result = CTFontManagerRegisterGraphicsFont(font, &error)
if !result {
print("[RegisterFont]\n\(error)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment