温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Xcode Objective-C: Download a custom font and display it in a UILabel
fonts objective-c xcode

其他 - Xcode Objective-C:下载自定义字体并将其显示在UILabel中

发布于 2020-04-05 00:33:36

首先:是否可以下载自定义字体并将其显示在UILabel中?

我正在使用此代码从Internet下载自定义字体并将其显示在UILabel中,但是它不起作用。

#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  

无论如何,我遇到此错误: 无法加载字体:操作无法完成。无效的论点

在自定义字体的位置,我获得了默认的iOS字体。

查看更多

提问者
Lifetronic
被浏览
179
Panway 2020-02-03 12:17

当然,可以下载自定义字体并将其显示在UILabel中,这是我的代码,效果很好:

步骤1:假设字体文件已保存在沙箱路径中Documents / StarsFighters.ttf,请加载字体并获取字体名称(在YOUR_CLASS .m文件中):

+ (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;
}

第二步:使用自定义字体

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];