Skip to content

Instantly share code, notes, and snippets.

@eoghain
Last active June 20, 2021 14:29
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eoghain/1dbbe0d47ce31189e14c058df1488d0d to your computer and use it in GitHub Desktop.
Save eoghain/1dbbe0d47ce31189e14c058df1488d0d to your computer and use it in GitHub Desktop.
A UIFont extension in swift to load fonts from within a bundle
import UIKit
public extension UIFont {
class func loadAllFonts(bundleIdentifierString: String) {
registerFontWithFilenameString(filenameString: "icon-font.ttf", bundleIdentifierString: bundleIdentifierString)
// Add more font files here as required
}
static func registerFontWithFilenameString(filenameString: String, bundleIdentifierString: String) {
if let frameworkBundle = Bundle(identifier: bundleIdentifierString) {
let pathForResourceString = frameworkBundle.path(forResource: filenameString, ofType: nil)
let fontData = NSData(contentsOfFile: pathForResourceString!)
let dataProvider = CGDataProvider(data: fontData!)
let fontRef = CGFont(dataProvider!)
var errorRef: Unmanaged<CFError>? = nil
if (CTFontManagerRegisterGraphicsFont(fontRef, &errorRef) == false) {
print("Failed to register font - register graphics font failed - this font may have already been registered in the main bundle.")
}
}
else {
print("Failed to register font - bundle identifier invalid.")
}
}
}
@eoghain
Copy link
Author

eoghain commented Dec 20, 2016

NOTE: The loadAllFonts(bundleIdentifierString:) method should only be called once. I'd wrap all the registerFontWithFilenamesString callse in a dispatch_once method but Swift3 doesn't have it anymore.

Possibly use this stackoverflow answer to extend DispatchQueue to add a DispatchQueue.once

@eoghain
Copy link
Author

eoghain commented Dec 20, 2016

You can add helper methods to this class to make it easier to get your fonts:

class func iconFont(size fontSize: CGFloat) -> UIFont {
        if let retval = UIFont(name: "icon-font", size: fontSize) {
            return retval;
        } else {
            return UIFont.systemFont(ofSize: fontSize)
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment