iOS 动态下载系统提供的中文字体
使用系统提供的中文字体,既可避免版权问题,又可以减小应用体积
#pragma mark - 判断字体是否已经被下载 - (BOOL)isFontDownLoaded:(NSString *)fontName{ UIFont *font = [UIFont fontWithName:fontName size:12.0]; if (font && [font.fontName compare:fontName] == NSOrderedSame) { return YES; } else{ return NO; } } #pragma mark - - (void)downLoadFont{ //如果字体已经被下载过了,则可以直接使用,否则我们需要先准备下载字体API需要的一些参数 NSString *fontName = @"FZLTTHK-GBK1.0"; //用自体的名字创建一个Dictionary NSMutableDictionary *attrs = [NSMutableDictionary dictionaryWithObjectsAndKeys:fontName,kCTFontNameAttribute, nil]; //创建一个字体描述对象CTFontDescriptorRef CTFontDescriptorRef desc = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)attrs); //将字体描述对象放到一个NSMutableArray中 NSMutableArray *descs = [NSMutableArray arrayWithCapacity:0]; [descs addObject:(__bridge id)desc]; CFRelease(desc); //字体下载 __block BOOL errorDuringDownLoad = NO; CTFontDescriptorMatchFontDescriptorsWithProgressHandler((__bridge CFArrayRef)descs, NULL, ^bool(CTFontDescriptorMatchingState state, CFDictionaryRef _Nonnull progressParameter) { double progress = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue]; switch (state) { case kCTFontDescriptorMatchingDidBegin: { NSLog(@"字体已经匹配"); } break; case kCTFontDescriptorMatchingDidFinish: { if (!errorDuringDownLoad) { NSLog(@"字体:%@下载完成",fontName); } } break; case kCTFontDescriptorMatchingWillBeginQuerying: { } break; case kCTFontDescriptorMatchingStalled: { } break; case kCTFontDescriptorMatchingWillBeginDownloading: { NSLog(@"字体开始下载"); } case kCTFontDescriptorMatchingDownloading: { NSLog(@"下载进度:%2f%%",progress); } break; case kCTFontDescriptorMatchingDidFinishDownloading: { NSLog(@"字体下载完成"); dispatch_async(dispatch_get_main_queue(), ^{ //可以在这里修改UI控件的字体 }); } break; case kCTFontDescriptorMatchingDidMatch: { } break; case kCTFontDescriptorMatchingDidFailWithError: { errorDuringDownLoad = YES; NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError]; if (error == nil) { NSLog(@"%@",[error description]); } else{ NSLog(@"ERROR MESSAGE IS NOT AVAILABLE!"); } } break; default: break; } return YES; }); }
在下载完成后开始使用字体,一般将使用字体的代码放在 kCTFontDescriptorMatchingDidFinishDownloading 这个判断条件中。
字体下载完成后修改UI有两种方式:
1.用GCD来修改
2.可以发送通知来通知相应的Controller