Links

Using custom UIFont on the fly

Here is yet another code snippet to add a custom font in UIFonts list without previously adding it in your app.plist file, useful while working with library projects and downloading font on the fly.
    NSArray *arrFont = @[@"Comic Sans MS.ttf",@"Tahoma.ttf"];
    
    for (NSString *str in arrFont) {
        
        NSString *fontPath = [[NSBundle mainBundle] pathForResource:BUNDLE_NAME ofType:@"bundle"];
        
        NSData *inData = [NSData dataWithContentsOfFile:[fontPath stringByAppendingFormat:@"/%@",str]];
        CFErrorRef error;
        CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge 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);
    }

Post a Comment