Skip to content

Instantly share code, notes, and snippets.

@mergesort
Last active August 29, 2015 14:06
Show Gist options
  • Save mergesort/245fa777d2e444fb82e2 to your computer and use it in GitHub Desktop.
Save mergesort/245fa777d2e444fb82e2 to your computer and use it in GitHub Desktop.
Can't get custom fonts to load once successfully registered with CTFontManagerRegisterGraphicsFont, help?
NSInteger const FontNotLoadedError = 101;
NSInteger const FontDoesNotExistError = 102;
NSString * const fontErrorDomain = @"FontError";
static NSDictionary *registeredFonts;
+ (UIFont *)customFontNamed:(NSString *)fontName size:(CGFloat)size
{
UIFont *font;
if ([registeredFonts[fontName] boolValue])
{
font = [UIFont fontWithName:fontName size:size];
}
else
{
NSError *error = [self loadFontNamed:fontName];
if (error)
{
DDLogError(@"An error occurred loading the font %@. Error: %@", fontName, error);
}
else
{
font = [UIFont fontWithName:fontName size:size];
}
}
return font;
}
+ (NSError *)loadFontNamed:(NSString *)fontName
{
if (!registeredFonts)
{
registeredFonts = [NSDictionary dictionary];
}
if (registeredFonts[fontName])
{
return nil;
}
NSString *fontFilePath = [listIconsPath() stringByAppendingPathComponent:fontName];
if ([JFFileManager isFileAtPath:fontFilePath])
{
NSData *fontData = [JFFileManager contentOfFileAtPath:fontFilePath];
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)fontData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
NSError *loadingError = nil;
if (!CTFontManagerRegisterGraphicsFont(font, &error))
{
CFStringRef errorDescription = CFErrorCopyDescription(error);
NSString *errorDescriptionString = (__bridge NSString *)errorDescription;
if (errorDescriptionString.length > 0)
{
loadingError = [NSError errorWithDomain:fontErrorDomain code:FontNotLoadedError userInfo:@{ NSLocalizedDescriptionKey : errorDescriptionString }];
}
CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
if (!loadingError)
{
NSMutableDictionary *mutableRegisteredFonts = [registeredFonts mutableCopy];
mutableRegisteredFonts[fontName] = @YES;
registeredFonts = [mutableRegisteredFonts copy];
}
return loadingError;
}
else
{
return [NSError errorWithDomain:fontErrorDomain code:FontDoesNotExistError userInfo:@{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"No font exists at the resource path %@", fontFilePath] }];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment