前言
最近遇到一個(gè)需求倘是,要改掉app的字體,一個(gè)一個(gè)改不太現(xiàn)實(shí)袭艺,由于一直用的系統(tǒng)字體搀崭,于是就想到了用運(yùn)行時(shí)來(lái)修改字體(僅限于純代碼的APP),閑話少說(shuō),直接上代碼瘤睹。
-
方法交換
首先創(chuàng)建一個(gè)UIfont
的category
升敲,把自己寫(xiě)的代碼放在category
里面(方法交換要寫(xiě)到load里面)
@implementation UIFont (MyFont)
+ (void)load {
Method myFontSize = class_getClassMethod(self, @selector(myFontOfSize:));
Method systemFontSize = class_getClassMethod(self, @selector(systemFontOfSize:));
method_exchangeImplementations(myFontSize, systemFontSize);
}
+ (UIFont *)myFontOfSize:(CGFloat)fontSize{
UIFont *font = [UIFont fontWithName:@"STHeitiTC-Light" size:fontSize];
return font;
}
Method myFontSize = class_getClassMethod(self, @selector(myFontOfSize:));
這句代碼是通過(guò)運(yùn)行時(shí)獲取自己寫(xiě)的方法,然后獲取系統(tǒng)方法Method systemFontSize = class_getClassMethod(self, @selector(systemFontOfSize:));
最后進(jìn)行方法交換
method_exchangeImplementations(myFontSize, systemFontSize);
-
方法使用
下面是控制器里的代碼轰传,也就是創(chuàng)建的標(biāo)簽控制器
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label1;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UILabel *label = [[UILabel alloc] init];
label.text = @"代碼標(biāo)簽";
label.textAlignment = NSTextAlignmentCenter;
label.bounds = CGRectMake(0, 0, 100, 30);
label.center = CGPointMake(self.view.center.x, 100);
[self.view addSubview:label];
_label1.font = [UIFont systemFontOfSize:16];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
運(yùn)行以后的截圖
通過(guò)運(yùn)行時(shí)來(lái)改變系統(tǒng)的字體驴党,僅適用于純代碼寫(xiě)的Label
,xib拖拽的控件不起作用获茬,需要手動(dòng)調(diào)用一下系統(tǒng)的方法systemFontSize:
才能起作用港庄,例如xib標(biāo)簽1的字體改變了,而xib標(biāo)簽2的字體沒(méi)有改變恕曲,因?yàn)?strong>xib標(biāo)簽1調(diào)用了一下systemFontSize:
方法鹏氧。