产品让把APP中的字体替换为Roboto,首先想到给UIFont添加分类,利用runtime进行方法替换,将使用systemFontOfSize和boldSystemFontOfSize方法设置字体的地方替换为Roboto字体
具体步骤:
1.先将Roboto-Medium.ttf 和 Roboto-Regular.ttf 两个字体导入工程,双击安装,并在info.plist中添加Fonts provided by application,并在其下添加Roboto-Medium.ttf 和Roboto-Regular.ttf ,如图
2. 新建UIFont分类,并在.m中添加如下代码,当然由于要使用runtime,需 #import <objc/runtime.h>
+(void)load{
//保证线程安全
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method originalMethod =class_getClassMethod([self class],@selector(systemFontOfSize:));
Method swapMethod =class_getClassMethod([self class],@selector(robotoFontOfSize:));
method_exchangeImplementations(originalMethod, swapMethod);
Method originalBoldMethod =class_getClassMethod([self class],@selector(boldSystemFontOfSize:));
Method swapBoldMethod =class_getClassMethod([self class],@selector(boldRobotoFontOfSize:));
method_exchangeImplementations(originalBoldMethod, swapBoldMethod);
});
}
+(UIFont*)robotoFontOfSize:(CGFloat)size{
UIFont *font = [self fontWithName:@"Roboto-Regular" size:size];
return font;
}
+(UIFont*)boldRobotoFontOfSize:(CGFloat)size{
UIFont*font = [self fontWithName:@"Roboto-Medium" size:size];
return font;
}
将头文件导入项目.pch,运行,完美~ 稍等,怎么有的字体变了有的没变。。。
经排查,xib和storyboard设置的字体是不会走systemFontOfSize和boldSystemFontOfSize的
于是只能从awakeFromNib入手,在执行awakeFromNib重新设置字体
新建UILabel分类,添加如下代码
+ (void)load{
//保证线程安全
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
//拿到系统方法
SEL orignalSel3 =@selector(awakeFromNib);
Method orignalM3 =class_getInstanceMethod(class, orignalSel3);
SEL swizzledSel3 =@selector(testFontAwakeFromNib);
Method swizzledM3 =class_getInstanceMethod(class, swizzledSel3);
BOOL didAddMethod3 =class_addMethod(class, orignalSel3,method_getImplementation(swizzledM3),method_getTypeEncoding(swizzledM3));
if(didAddMethod3) {
class_replaceMethod(class, swizzledSel3, method_getImplementation(orignalM3), method_getTypeEncoding(orignalM3));
}else{
method_exchangeImplementations(orignalM3, swizzledM3);
}
});
}
#pragma mark -使用的替换方法
- (void)testFontAwakeFromNib{
[self testFontAwakeFromNib];
self.font = [UIFont systemFontOfSize:16];
}
运行,真的完美了~
感谢 https://www.jianshu.com/p/b17adc8f3f13?utm_source=oschina-app~~~