1. 導入想要的的字體包(.ttf格式)到你的項目中,勾選紅色箭頭標記的copy items if needed等
Paste_Image.png
2. 在項目的info文件中添加這個字體包
- 添加Fonts provided by application字段,是數(shù)組類型的
- 內(nèi)部的每一個item對應一個字體,key就是item0/1/2...,value就是你導入的字體包文件名
- 可以添加多個字體包
Paste_Image.png
3. 在build phases -> copy bundle resources中添加導入的包(一般系統(tǒng)會自動添加進來)
Paste_Image.png
4. 在程序中加入一段代碼,在輸出的內(nèi)容中查看你導入的字體包在項目中的family name(會有很多,仔細查找,可以用command + F 搜索一下關鍵字母),這個名字是以后設置字體時要用的 , 注意這里有一個font name,還有一個family name,我們要用family name,否則看不到效果
// 0. 查看自定義的字體在系統(tǒng)中的family name
NSArray *familyNames =[[NSArray alloc]initWithArray:[UIFont familyNames]];
NSArray *fontNames;
NSInteger indFamily, indFont;
NSLog(@"[familyNames count]===%zd",[familyNames count]);
for(indFamily=0;indFamily<[familyNames count];++indFamily)
{
NSLog(@"Family name: %@", [familyNames objectAtIndex:indFamily]);
fontNames =[[NSArray alloc]initWithArray:[UIFont fontNamesForFamilyName:[familyNames objectAtIndex:indFamily]]];
for(indFont=0; indFont<[fontNames count]; ++indFont)
{
NSLog(@"Font name: %@",[fontNames objectAtIndex:indFont]);
}
}
/** 找到的字體名字:
* Family name: Agency FB
2015-11-09 12:27:38.266 1109--01--自定義的字體[6957:481083] Font name: AgencyFB-Bold
2015-11-09 12:27:38.266 1109--01--自定義的字體[6957:481083] Font name: AgencyFB-Reg
*/
Paste_Image.png
5. 使用示例
- 從第四步可以看到導入的字體包的名字是Agency FB
- 使用代碼:創(chuàng)建一個lable,設置上面的文字字體
// 2.創(chuàng)建一個label
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(100, 100, 100, 100);
label.backgroundColor = [UIColor redColor];
label.text = @"hahahahahahaha";
[self.view addSubview:label];
//3. 使用自定義的字體
label.font = [UIFont fontWithName:@"Agency FB" size:20];
效果圖:
Paste_Image.png
6. 實用技巧:
- 建議把字體包的family name定義一個宏,方便每次使用,有系統(tǒng)提示
#define Font_Agency @"Agency FB"
// 使用的時候就方便很多了,
//3. 使用自定義的字體
label.font = [UIFont fontWithName:@"Agency FB" size:20];
label.font = [UIFont fontWithName:Font_Agency size:20];
- 或者可以這樣定義宏(我比較喜歡這樣使用),更加方便使用
#define XLFontAgencyFB(font) [UIFont fontWithName:@"Agency FB" size:font]
// 使用的時候更加方便了
self.totalDistanceLabel.font = XLFontAgencyFB(16);