iOS工程中引入iconfont字体库图标的备忘
在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的图标了。