iOS项目中使用自定义的字体

2016-11-15  本文已影响68人  shannoon

1. 导入想要的的字体包(.ttf格式)到你的项目中,勾选红色箭头标记的copy items if needed等

Paste_Image.png

2. 在项目的info文件中添加这个字体包

Paste_Image.png

3. 在build phases -> copy bundle resources中添加导入的包(一般系统会自动添加进来)

Paste_Image.png

4. 在程序中加入一段代码,在输出的内容中查看你导入的字体包在项目中的family name(会有很多,仔细查找,可以用command + F 搜索一下关键字母),这个名字是以后设置字体时要用的 , 注意这里有一个font name,还有一个family name,我们要用family name,否则看不到效果

// 0. 查看自定义的字体在系统中的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. 使用示例

    // 2.创建一个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. 实用技巧:

#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);

7. 你可以在http://www.webpagepublicity.com/free-fonts.html 下载更多ttf字体

上一篇 下一篇

猜你喜欢

热点阅读