18

I've seen this question asked and answered numerous times, but I haven't seen a real answer. The common "solutions" are:

  • Add the font to the application bundle and register it in the info.plist file.
  • Use a custom font parsing and rendering library (like the Zynga's FontLabel).
  • It cannot be done.

So the question is: How to dynamically load a font under iOS? Loading the font "dynamically" means loading any given font which is not known at the time of the app's compilation.

2
  • looked into CTFontManagerCreateFontDescriptorsFromURL?
    – Bejmax
    Dec 27, 2012 at 3:01
  • See stackoverflow.com/a/12497630/724514. Just tried it out and was able to load and use the font. For purposes of "loading any given font not known at the time of the app's compilation", you can download the font and save it in the Documents directory, then follow the example in your code.
    – bobnoble
    Dec 27, 2012 at 3:05

6 Answers 6

25

Fonts can easily be dynamically loaded from any location or any byte stream. See the article here: http://www.marco.org/2012/12/21/ios-dynamic-font-loading

NSData *inData = /* your font-file data */;
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);
}
CFRelease(font);
CFRelease(provider);
  • You don't have to put the font in your bundle.
  • You don't have to explicitly register the font in your info.plist.

See also: https://developer.apple.com/library/mac/#documentation/Carbon/Reference/CoreText_FontManager_Ref/Reference/reference.html#//apple_ref/doc/uid/TP40008278

https://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CGFont/Reference/reference.html#//apple_ref/c/func/CGFontCreateWithDataProvider

7
  • is it possible to specify the name to register the font as when loading?
    – user102008
    May 15, 2013 at 5:37
  • @user102008 It doesn't seem to be possible.
    – Ark-kun
    May 15, 2013 at 14:14
  • @user102008 get the name from the CGFontRef object instead – CGFontCopyFullName.
    – adib
    Feb 14, 2016 at 6:26
  • @adib: I was talking about setting the name, not getting the name
    – user102008
    Feb 14, 2016 at 6:29
  • can this method be used somehow with storyboards/xib as well? Or do all my custom fonts have to be loaded at app startup then?
    – swalkner
    May 17, 2016 at 5:42
10

Great time for a recent post from Marco titled Loading iOS fonts dynamically.

NSData *inData = /* your decrypted font-file data */;
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);
}
CFRelease(font);
CFRelease(provider);
3
  • 2
    It's a very fun situation. I discovered Marco's post and went to post this same code as an answer to a bunch of questions on SO. But then I thought that it might be better to create a self-answered question so that the answer is more easily discoverable. Then moderator removed my own answer with to my own question with that same code =(
    – Ark-kun
    Dec 28, 2012 at 0:20
  • is it possible to specify the name to register the font as when loading?
    – user102008
    May 15, 2013 at 5:36
  • you'll need #import <CoreText/CoreText.h>
    – MrTristan
    Jan 8, 2018 at 15:56
2
// Note : add "CoreText.framework" into your project to support following code

// Put loadCustomFont function inside app delegate or any shared class to access any where in code...

    -(void)loadCustomFont:(NSMutableArray *)customFontFilePaths{

        for(NSString *fontFilePath in customFontFilePaths){

            if([[NSFileManager defaultManager] fileExistsAtPath:fontFilePath]){

                NSData *inData = [NSData dataWithContentsOfFile:fontFilePath];
                CFErrorRef error;
                CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)inData);
                CGFontRef font = CGFontCreateWithDataProvider(provider);
                // NSString *fontName = (__bridge NSString *)CGFontCopyFullName(font);
                if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
                    CFStringRef errorDescription = CFErrorCopyDescription(error);
                    NSLog(@"Failed to load font: %@", errorDescription);
                    CFRelease(errorDescription);
                }
                CFRelease(font);
                CFRelease(provider);
            }
        }
    }

    // Use as follow inside your view controller...

    - (void)viewDidLoad
    {
        [super viewDidLoad];

        // pass all font files name into array which you want to load dynamically...
        NSMutableArray *customFontsPath = [[NSMutableArray alloc] init];
        NSArray *fontFileNameArray = [NSArray arrayWithObjects:@"elbow_v001.ttf",@"GothamRnd-MedItal.otf", nil];

        for(NSString *fontFileName in fontFileNameArray){

            NSString *fileName = [fontFileName stringByDeletingPathExtension];
            NSString *fileExtension = [fontFileName pathExtension];
            [customFontsPath addObject:[[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension]];
        }


        AppDelegate *appDel = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        // load custom font into memory...
        [appDel loadCustomFont:customFontsPath];

        // Use font as below
        [lblName setFont:[UIFont fontWithName:@"Elbow v100" size:15.0]];
        [lblName2 setFont:[UIFont fontWithName:@"Gotham Rounded" size:20.0]];
    }
3
  • 2
    if you're gonna do this, why not use CTFontManagerRegisterFontsForURL()?
    – user102008
    May 15, 2013 at 5:38
  • @user102008 because you won't be able to know what was the font that you registered from that URL. Going via CGFontRef allows you to get the name and use normal UIFont methods afterwards.
    – adib
    Feb 14, 2016 at 6:25
  • 1
    If the app hangs, use this: stackoverflow.com/questions/24900979/… Feb 16, 2016 at 14:11
2

Downloading a TTF file from server?

IF you are downloading a TTF file then you can do following to register your custom fonts with iOS Font Manager, this piece of code also takes care of TTF file updates (font updates):

+(void)registerFontsAtPath:(NSString *)ttfFilePath
{
    NSFileManager * fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:ttfFilePath] == YES)
    {
        [UIFont familyNames];//This is here for a bug where font registration API hangs for forever.

        //In case of TTF file update : Fonts are already registered, first de-register them from Font Manager
        CFErrorRef cfDe_RegisterError;
       bool fontsDeregistered = CTFontManagerUnregisterFontsForURL((__bridge CFURLRef)[NSURL fileURLWithPath:ttfFilePath], kCTFontManagerScopeNone, &cfDe_RegisterError);


        //finally register the fonts with Font Manager,
        CFErrorRef cfRegisterError;
        bool fontsRegistered= CTFontManagerRegisterFontsForURL((__bridge CFURLRef)[NSURL fileURLWithPath:ttfFilePath], kCTFontManagerScopeNone, &cfRegisterError);
}
2

Here is an updated answer of @mt81 for Swift 3:

guard
    let path = "Path to some font file",
    let fontFile = NSData(contentsOfFile: path)
else {
    print "Font file not found?"
}

guard let provider = CGDataProvider(data: fontFile)
else {
    print "Failed to create DataProvider"
}

let font = CGFont(provider)
let error: UnsafeMutablePointer<Unmanaged<CFError>?>? = nil

guard CTFontManagerRegisterGraphicsFont(font, error) else {
    guard
        let unError = error?.pointee?.takeUnretainedValue(),
        let description = CFErrorCopyDescription(unError)
    else {
        print "Unknown error"
    }
    print description
}
1

Here the swift version:

let inData: NSData = /* your font-file data */;
let error: UnsafeMutablePointer<Unmanaged<CFError>?> = nil
let provider = CGDataProviderCreateWithCFData(inData)
if let font = CGFontCreateWithDataProvider(provider) {
    if (!CTFontManagerRegisterGraphicsFont(font, error)) {
        if let unmanagedError = error.memory {
            let errorDescription = CFErrorCopyDescription(unmanagedError.takeUnretainedValue())
            NSLog("Failed to load font: \(errorDescription)");
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.