產(chǎn)品讓把APP中的字體替換為Roboto,首先想到給UIFont添加分類,利用runtime進(jìn)行方法替換,將使用systemFontOfSize和boldSystemFontOfSize方法設(shè)置字體的地方替換為Roboto字體
具體步驟:?
1.先將Roboto-Medium.ttf 和 Roboto-Regular.ttf 兩個(gè)字體導(dǎo)入工程,雙擊安裝,并在info.plist中添加Fonts provided by application,并在其下添加Roboto-Medium.ttf 和Roboto-Regular.ttf ,如圖

2. 新建UIFont分類,并在.m中添加如下代碼,當(dāng)然由于要使用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;
}
將頭文件導(dǎo)入項(xiàng)目.pch,運(yùn)行,完美~? ? 稍等,怎么有的字體變了有的沒變。。。
經(jīng)排查,xib和storyboard設(shè)置的字體是不會(huì)走systemFontOfSize和boldSystemFontOfSize的
于是只能從awakeFromNib入手,在執(zhí)行awakeFromNib重新設(shè)置字體
新建UILabel分類,添加如下代碼
+ (void)load{
? ? //保證線程安全
? ? static dispatch_once_t onceToken;
? ? dispatch_once(&onceToken, ^{
? ? ? ? Class class = [self class];
? ? ? ? //拿到系統(tǒng)方法
? ? ? ? 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];
}
運(yùn)行,真的完美了~
感謝?http://www.itdecent.cn/p/b17adc8f3f13?utm_source=oschina-app~~~