iOS工程中引入iconfont字体库图标的备忘

作者: shaneZhang 分类: ios技术 发布时间: 2016-12-15 10:52

在iOS工程中引用iconFont字体库图标是现在开发中常见的一种开发方式了。今天就在这里简单示意一下如何引入iconfont字体库图标的使用。

我们拿到一个ttf的字体库后,加入到工程中,新建一个字体库的工具类,用来引用注册该字体库。


#import "ZCCustomAlertViewIconFont.h"
#import 

@interface ZCCustomAlertViewIconFont()
@end

@implementation ZCCustomAlertViewIconFont
+ (UIFont *)iconFontWithSize:(CGFloat)size
{
#ifndef DISABLE_FONTAWESOME_AUTO_REGISTRATION
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
        NSURL *fontUrl = [bundle URLForResource:@"zhangyuqing" withExtension:@"ttf"];
        [self registerIconFontWithURL:fontUrl];
    });
#endif
    
    UIFont *font = [UIFont fontWithName:@"zhangyuqing" size:size];
    NSAssert(font, @"UIFont object should not be nil, check if the font file is added to the application bundle and you're using the correct font name.");
    return font;
}

+ (void)registerIconFontWithURL:(NSURL *)url
{
    NSAssert([[NSFileManager defaultManager] fileExistsAtPath:[url path]], @"Font file doesn't exist");
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)url);
    CGFontRef newFont = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CFErrorRef error = NULL;
    CTFontManagerRegisterGraphicsFont(newFont, &error);
    CGFontRelease(newFont);
    
    if (error) {
        CFRelease(error);
    }
}
@end

在工程中如何使用该图标呢?请看下面的代码示例。


    self.tipsImageLabel = [[UILabel alloc]init];
    [self.contentView addSubview:self.tipsImageLabel];
    
    [self.tipsImageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView.mas_top).offset(20);
        make.centerX.mas_equalTo(self.contentView.mas_centerX).offset(0);
        make.width.mas_equalTo(32);
        make.height.mas_equalTo(32);
    }];

    self.tipsImageLabel.font = [ZCCustomAlertViewIconFont iconFontWithSize:32];
    self.tipsImageLabel.textColor = [UIColor colorWithHexString:@"c8c8ce"];
    self.tipsImageLabel.text = @"\U0000e615";

然后这样就可以正确地显示编号为e615的图标了。

本页面支持繁体中文友好显示:iOS工程中引入iconfont字体库图标的备忘

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注