iOS开发技术分享

iOS使用自定义字体

2017-02-24  本文已影响754人  喵子G

要添加自定义字体,首先是要有字体库资源,XXX.ttf 这种字体库文件,要是没有的话,可以去网上下载一下,大多都是收费的,也有一些免费的可以下载,这里我用的是我在网上下载的AaQingCong.ttf。这里自定义字体最大的问题就是找不到对应的字体库,不能够完全按照自己的需求自定义字体。

首先下载字体库,然后把自己库托到项目里:


ranh

接下来在 info.plist 中添加 Fonts provided by application - AaQingCong.ttf


WX20170224-183409.png
最后在TARGETS-Build Phases-Copy Bundle Resources 添加字体库文件:
WX20170224-183630.png

现在字体库就成功添加了,要使用特定体字代码如下:

cell.textLabel.font = [UIFont fontWithName:@"XXX" size:18];

至于自己添加的字体库的名字叫什么这个并不能看字体库的文件名来判断,我是通过一个小Demo,遍历所有的字体,把它们的英文和汉子字体效果都展示出来,找到自己添加的:


WX20170224-184121.png

如图,这个就是我刚刚添加的自定义字体,系统的默认字体,汉子除了粗细之外都没有别的字体变化。
获取所有字体代码如下:

// 自定义字体Family模型
@interface JKRFontFamily : NSObject

@property (nonatomic, copy) NSString *familyName;                 /// familyName
@property (nonatomic, strong) NSArray<NSString *> *fontNames;     /// 该family下所有字体的名字

@end

// 获取所有的字体
- (void)loadData {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (NSString *familyName in [UIFont familyNames]) {
            JKRFontFamily *family = [[JKRFontFamily alloc] init];
            family.familyName = familyName;
            family.fontNames = [UIFont fontNamesForFamilyName:familyName];
            [_fontFamilies addObject:family];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    });
}

//用tableView展示,每个section是一个family
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.fontFamilies.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fontFamilies[section].fontNames.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.fontFamilies[section].familyName;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = [UIFont fontWithName:self.fontFamilies[indexPath.section].fontNames[indexPath.row] size:18];
    cell.textLabel.text = [NSString stringWithFormat:@"字体展示/Font show:%@", self.fontFamilies[indexPath.section].fontNames[indexPath.row]];
    return cell;
}
上一篇下一篇

猜你喜欢

热点阅读