Warm tip: This article is reproduced from stackoverflow.com, please click
fonts objective-c xcode

Xcode Objective-C: Download a custom font and display it in a UILabel

发布于 2020-04-05 00:22:23

First of all: Is it possible to download a custom font and display it in a UILabel?

I'm using this code to download a custom font from internet and display it in a UILabel but it does not work.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize txt_UserName;

- (void)viewDidLoad {
    [super viewDidLoad];

    // 1
    NSString *dataUrl = @"https://dl.dafont.com/dl/?f=stars_fighters";
    NSURL *url = [NSURL URLWithString:dataUrl];

    // 2
    NSURLSessionDataTask *downloadTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // 4: Handle response here
        if (error == nil) {
            NSLog(@"no error!");
            if (data != nil) {
                NSLog(@"There is data!");
                [self loadFont:data];
            }
        } else {
            NSLog(@"%@", error.localizedDescription);
        }
    }];

    // 3
    [downloadTask resume];


}

- (void)loadFont:(NSData *)data
{
    NSData *inData = data;
    CFErrorRef error;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
    CGFontRef font = CGFontCreateWithDataProvider(provider);
    if(!CTFontManagerRegisterGraphicsFont(font, &error)){
        CFStringRef errorDescription = CFErrorCopyDescription(error);
        NSLog(@"Failed to load font: %@", errorDescription);
      //  CFRelease(errorDescription);
    }
//    CFRelease(font);
 //   CFRelease(provider);

    CTFontRef ctFont = CTFontCreateWithGraphicsFont(font, 30, NULL, NULL);
    UIFont *uiFont = CFBridgingRelease(ctFont);

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.txt_UserName setFont:uiFont];
    });

    [self fontTest];
}

- (void)fontTest
{
    NSArray *fontFamilies = [UIFont familyNames];
    for (int i = 0; i < [fontFamilies count]; i++) {
        NSString *fontFamily = [fontFamilies objectAtIndex:i];
        NSArray *fontNames = [UIFont fontNamesForFamilyName:[fontFamilies objectAtIndex:i]];
        NSLog (@"%@: %@", fontFamily, fontNames);
    }
}

@end  

Anyway I'm getting this error: Failed to load font: The operation couldn’t be completed. Invalid argument

At the place of the custom font I get a default iOS font.

Questioner
Lifetronic
Viewed
149
Panway 2020-02-03 12:17

Of course it's possible to download a custom font and display it in a UILabel,here is my code that works well:

step 1: Assuming the font file has been saved in the sandbox path Documents / StarsFighters.ttf, load the font and get font name(in YOUR_CLASS .m file):

+ (NSString *)loadFontAndReturnFontName {
    NSString *imgFilePath = [NSString stringWithFormat:@"%@/Documents/StarsFighters.ttf",NSHomeDirectory()];
    NSURL *fontUrl = [NSURL fileURLWithPath:imgFilePath];
    CGDataProviderRef fontDataProvider =  CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
    CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CTFontManagerRegisterGraphicsFont(fontRef, NULL);
    NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
    return fontName;
}

step2: use custom font

NSString *fontname = [YOUR_CLASS loadFontAndReturnFontName];
//fontname is @"StarsFighters",best set it to a global variable or save it
YOUR_LABEL.font = [UIFont fontWithName:fontname size:18.0];