热门搜索 :
考研考公
您的当前位置:首页正文

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

来源:东饰资讯网

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

Paste_Image.png

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

  • 添加Fonts provided by application字段,是数组类型的
  • 内部的每一个item对应一个字体,key就是item0/1/2...,value就是你导入的字体包文件名
  • 可以添加多个字体包
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. 使用示例

  • 从第四步可以看到导入的字体包的名字是Agency FB
  • 使用代码:创建一个lable,设置上面的文字字体
    // 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. 实用技巧:

  • 建议把字体包的family name定义一个宏,方便每次使用,有系统提示
#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. 你可以在 下载更多ttf字体

Top