iOS字體全局替換

產(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~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容