改變整個APP的所有控件的字體分為兩種情況:
1.在程序啟動的時候的改變字體,并且在程序運行過程中不需要再改變。
2.在程序運行的過程中動態改變APP的字體(比如微信等)。
一、只是改變一次
有兩種方法:
1.使用runtime改變,不能對控件進行單獨設置。(可以設置控件的tag值進行判斷處理)
2.重寫 控件的 initWithFrame方法。如果對控件進行單獨處理的方法與重寫的方法重復,會使用單獨處理的方法。
使用runtime
創建UIlabel的子類
#import "UILabel+changeFont.h"
#import <objc/runtime.h>
@implementation UILabel (changeFont)
+ (void)load {
//方法交換應該被保證,在程序中只會執行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//獲得viewController的生命周期方法的selector
SEL systemSel = @selector(willMoveToSuperview:);
//自己實現的將要被交換的方法的selector
SEL swizzSel = @selector(myWillMoveToSuperview:);
//兩個方法的Method
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
//首先動態添加方法,實現是被交換的方法,返回值表示添加成功還是失敗
BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
if (isAdd) {
//如果成功,說明類中不存在這個方法的實現
//將被交換方法的實現替換到這個并不存在的實現
class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
} else {
//否則,交換兩個方法的實現
method_exchangeImplementations(systemMethod, swizzMethod);
}
});
}
- (void)myWillMoveToSuperview:(UIView *)newSuperview {
[self myWillMoveToSuperview:newSuperview];
if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
return;
}
if (self) {
if (self.tag == 10086) {
self.font = [UIFont systemFontOfSize:self.font.pointSize];
} else {
self.font = [UIFont systemFontOfSize:30];
self.backgroundColor = [UIColor redColor];
}
}
}
@end
重寫 控件的 initWithFrame方法
創建UIlabel的子類
#import "UILabel+changeFont.h"
@implementation UILabel (changeFont)
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self setGlobalFont];
}
return self;
}
// 如果是xib或storyboard創建會走該方法
- (void)awakeFromNib
{
[super awakeFromNib];
[self setGlobalFont];
}
- (void)setGlobalFont
{
// 不改變 textfield
if ([self isKindOfClass:NSClassFromString(@"UITextFieldLabel")]) {
return;
}
// 不改變 button
if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
return;
}
self.font = [UIFont systemFontOfSize:30];
self.backgroundColor = [UIColor redColor];
}
@end
二、動態改變APP所有字體
重寫控件的 initWithFrame方法,添加一個通知,在需要改變的時候 post這個通知就可以了。
創建UIlabel的子類
#import "UILabel+changeFont.h"
@implementation UILabel (changeFont)
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setGlobalFont) name:@"font" object:nil];
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setGlobalFont) name:@"font" object:nil];
}
- (void)setGlobalFont
{
if ([self isKindOfClass:NSClassFromString(@"UITextFieldLabel")]) {
return;
}
if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {
return;
}
self.font = [UIFont systemFontOfSize:30];
self.backgroundColor = [UIColor redColor];
}
@end