且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS:在运行时以编程方式添加自定义字体

更新时间:2023-10-03 08:09:10

I know this is an old question, but I was trying to do the same today and found a way using CoreText and CGFont.

First be sure you add the CoreText framework and

#import <CoreText/CoreText.h>

Then this should do it (in this example I am using a font I previously downloaded and saved to a fonts directory inside the Documents directory):

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentsDirectory = [paths objectAtIndex:0];
    NSString * fontPath = [documentsDirectory stringByAppendingPathComponent:@"Fonts/Chalkduster.ttf"];
    NSURL * url = [NSURL fileURLWithPath:fontPath];
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
    CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
    NSString * newFontName = (__bridge NSString *)CGFontCopyPostScriptName(newFont);
    CGDataProviderRelease(fontDataProvider);
    CFErrorRef error;
    CTFontManagerRegisterGraphicsFont(newFont, &error);
    CGFontRelease(newFont);

    UIFont * finalFont = [UIFont fontWithName:newFontName size:20.0f];

Hope it helps anyone stumbling across this question!