有三种方式:
一、使用系统随附的字体
在使用之前,先把支持的所有字体打印出来,确保存在再使用:
// 打印所有的系统已存在的字体
static void dumpAllFonts() {
NSInteger totalCount;
for (NSString *familyName in [UIFont familyNames]) {
NSArray *familyNameArr = [UIFont fontNamesForFamilyName:familyName];
NSLog(@"familyName:%@ count=%ld", familyName,[familyNameArr count]);
NSInteger tempCount = [familyNameArr count];
totalCount += tempCount;
for (NSString *fontName in familyNameArr) {
NSLog(@"++++ %@", fontName);
}
}
NSLog(@"totalCount=%ld",totalCount);
}
使用就很简单了:
[UIFont fontWithName:@"字体的名字" size:14]
二、从外界拖进来的静态字体(也就是你的UI给你的字体,.ttf或者.ttc等格式的文件)
在使用前双击资源文件,mac会默认用‘字体册’打开,这时你会看到一些相关信息:
接下来就是开始了:
1、把资源拖进工程
2、TARGETS->Info->添加‘Fonts provide by application’项,如下:
3、TARGETS->Build Phases ->Copy Bundle Resources
4、到这里再次打印所有的字体,应该可以找到目标字体名,然后就可以像使用已存在的系统字体那样使用了。
三、下载系统字体使用
使用系统的API先把字体下载下来,然后就可以像普通已安装字体使用了。
我是把下载字体的api简单地封装了一下,AsyDownloadSystemFont:
/**
* 下载系统提供的字体 (异步)
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedef void(^DownloadingBlock)(CGFloat progressValue);
typedef void(^DownloadSuccessBlock)(void);
typedef void(^DownloadErrocBlock)(NSString *errorMsg);
@interface AsyDownloadSystemFont : NSObject
/**
* 判断该字体有没有下载过
*
* @param fontName 字体名字 (不是文件夹的名字)
*
* @return Yes:已经下载过 NO:没有下载过
*/
+(BOOL)isExistWithFontName:(NSString *)fontName;
/**
* 异步下载系统提供的字体
*
* @param fontName 字体名字 (不是文件夹的名字)
* @param loadingCallBack 下载中的回调 (可以改变进度条的值)
* @param sucessCallBack 下载成功的回调 (可以进行UI刷新)
* @param errorCalBack 下载失败的回调
*/
+(void)asyDownLoadFontWithFontName:(NSString *)fontName
downloading:(DownloadingBlock)loadingCallBack
downloadSuccess:(DownloadSuccessBlock)sucessCallBack
downloadError:(DownloadErrocBlock)errorCalBack;
@end
#import "AsyDownloadSystemFont.h"
#import <CoreText/CoreText.h>
@implementation AsyDownloadSystemFont
#pragma mark - Public Methods
+(BOOL)isExistWithFontName:(NSString *)fontName {
UIFont *aFont = [UIFont fontWithName:fontName size:12.];
if (aFont && ([aFont.fontName compare:fontName] == NSOrderedDescending || [aFont.familyName compare:fontName] == NSOrderedSame)) {
NSLog(@"存在");
return YES;
}
NSLog(@"不存在");
return NO;
}
+(void)asyDownLoadFontWithFontName:(NSString *)fontName
downloading:(DownloadingBlock)loadingCallBack
downloadSuccess:(DownloadSuccessBlock)sucessCallBack
downloadError:(DownloadErrocBlock)errorCalBack {
//1、准备参数
//用字体的PostScript名字创建一个NSDicitonary
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);
//2、开始下载
CTFontDescriptorMatchFontDescriptorsWithProgressHandler((__bridge CFArrayRef)descs, NULL, ^bool(CTFontDescriptorMatchingState state, CFDictionaryRef _Nonnull progressParameter) {
__block BOOL errorDuringDownload = NO;
double progressValue = [[(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingPercentage] doubleValue];
if (state == kCTFontDescriptorMatchingDidBegin) {
//字体已经匹配
NSLog(@"字体已经匹配");
}else if (state == kCTFontDescriptorMatchingDidFinish) {
if (!errorDuringDownload) {
//字体下载完成
NSLog(@"字体下载完成 -");
dispatch_async(dispatch_get_main_queue(), ^{
if (sucessCallBack) {
sucessCallBack();
}
});
}
}else if (state == kCTFontDescriptorMatchingWillBeginDownloading) {
//字体开始下载
}else if (state == kCTFontDescriptorMatchingDidFinishDownloading) {
//字体下载完成 (可以在这里修改UI)
NSLog(@"字体下载完成 (可以在这里修改UI");
dispatch_async(dispatch_get_main_queue(), ^{
if (sucessCallBack) {
sucessCallBack();
}
});
}else if (state == kCTFontDescriptorMatchingDownloading) {
//下载中
NSLog(@"下载中");
dispatch_async(dispatch_get_main_queue(), ^{
if (loadingCallBack) {
loadingCallBack(progressValue);
}
});
}else if (state == kCTFontDescriptorMatchingDidFailWithError) {
NSString *errorMsg;
NSError *error = [(__bridge NSDictionary *)progressParameter objectForKey:(id)kCTFontDescriptorMatchingError];
if (!error) {
errorMsg = [errorMsg description];
}else {
errorMsg = @"Error Message Is Not Available!";
}
dispatch_async(dispatch_get_main_queue(), ^{
if (errorCalBack) {
errorCalBack(errorMsg);
}
});
NSLog(@"errorMsg=%@",errorMsg);
//设置标志
errorDuringDownload = YES;
}
return YES;
});
}
@end
下面就是具体的使用:
#import "DynamicViewController.h"
#import "AsyDownloadSystemFont.h"
#import "UIView+FrameHelp.h"
static NSArray *kFontNames() {
NSArray *fontNames = nil;
if (!fontNames) {
fontNames = @[
@"STXingkai-SC-Light",
@"DFWaWaSC-W5",
@"FZLTXHK--GBK1-0",
@"STLibian-SC-Regular",
@"LiHeiPro",
@"HiraginoSansGB-W3"
];
}
return fontNames;
}
static NSArray *kFontSamples() {
NSArray *fontSamples = nil;
if (!fontSamples) {
fontSamples = @[
@"汉体书写信息技术标准相",
@"容档案下载使用界面简单",
@"支援服务升级资讯专业制",
@"作创意空间快速无线上网",
@"兙兛兞兝兡兣嗧瓩糎",
@"㈠㈡㈢㈣㈤㈥㈦㈧㈨㈩"
];
}
return fontSamples;
}
@interface DynamicViewController () <UITableViewDataSource,UITableViewDelegate>
{
NSString *_fontName;
}
@property (nonatomic, retain) UITableView *kTableView;
@property (nonatomic, retain) UIProgressView *kProgress;
@property (nonatomic, retain) UITextView *kTextView;
@property (nonatomic, retain) UIActivityIndicatorView *kActivityView;
@end
@implementation DynamicViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
[self uiConfig];
}
#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [kFontNames() count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *fontName = kFontNames();
static NSString *cellId = @"cellId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
cell.textLabel.text = [fontName objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
_fontName = [kFontNames() objectAtIndex:indexPath.row];
BOOL isExist = [AsyDownloadSystemFont isExistWithFontName:_fontName];
if (isExist) {
NSString *text = [kFontSamples() objectAtIndex:indexPath.row];
[self refrshTextViewWithText:text];
}else {
NSString *samples = [kFontSamples() objectAtIndex:indexPath.row];
[AsyDownloadSystemFont asyDownLoadFontWithFontName:_fontName downloading:^(CGFloat progressValue) {
[self.kProgress setHidden:NO];
self.kProgress.progress = progressValue/100;
[self.kActivityView startAnimating];
} downloadSuccess:^{
[self.kProgress setHidden:YES];
[self.kActivityView stopAnimating];
[self refrshTextViewWithText:samples];
} downloadError:^(NSString *errorMsg) {
[self.kProgress setHidden:YES];
[self.kActivityView stopAnimating];
NSLog(@"errorMsg=%@",errorMsg);
}];
}
}
-(void)refrshTextViewWithText:(NSString *)text {
self.kTextView.font = [UIFont fontWithName:_fontName size:14.];
self.kTextView.text = text;
}
#pragma mark - Private Methods
-(void)uiConfig {
self.view.backgroundColor = [UIColor whiteColor];
self.kTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 400) style:UITableViewStylePlain];
self.kTableView.tableFooterView = [UIView new];
self.kTableView.dataSource = self;
self.kTableView.delegate = self;
self.kProgress = [[UIProgressView alloc] initWithFrame:CGRectMake((self.view.width-150)/2, self.view.height-100, 150, 10)];
self.kProgress.userInteractionEnabled = NO;
[self.kProgress setHidden:YES];
self.kTextView = [[UITextView alloc] initWithFrame:CGRectMake((self.view.width-150)/2, self.view.height-150, 150, 30)];
self.kActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.kActivityView.hidesWhenStopped = YES;
[self.view addSubview:self.kTableView];
[self.view addSubview:self.kProgress];
[self.view addSubview:self.kTextView];
self.navigationItem.titleView = self.kActivityView;
}
@end