Search code examples
iosfontscore-textfont-familycustom-font

Get font face from ttf file


In my iOS app I use custom fonts, dynamically loaded from files.

To use them in code, I need to know loaded fonts' families. So, is there any way to do it?

UPDATE:

I can't somehow hardcode font families, cause my app loads it from server. Of course, there is a way to pass font families in server response, but for now I'm looking for a better version that doesn't influence the server (doesn't need to change it).


Solution

  • Font loading I did...

    NSData *fontData = [NSData dataWithContentsOfFile:filePath];
    if (fontData) {
        // create font from loaded data and get it's postscript name
        CGDataProviderRef fontDataProvider = CGDataProviderCreateWithCFData((CFDataRef)fontData);
        CGFontRef loadedFont = CGFontCreateWithDataProvider(fontDataProvider);
        NSString *postScriptName = (NSString *)CGFontCopyPostScriptName(loadedFont);
    
        // if the font with same postscript name wasn't already registered - do it
        if (postScriptName && ![UIFont fontWithName:postScriptName size:10]) {
            NSError *error;
            if (!CTFontManagerRegisterGraphicsFont(loadedFont, (CFErrorRef *)&error)) {
                NSLog(@"Can't load font: %@", error);
            }
        }
    
        CGFontRelease(loadedFont);
        CGDataProviderRelease(fontDataProvider);
    }