在iOS开发中,经常会遇到过修改界面的UILabel上显示的字体的大小或者样式等等需求。当对于一个新的项目来说,可能单独的去修改UILabel上的字体工作量不是太大,但是当一个项目已经成熟或者十分庞大的时候,要是再想使用这种方法进行修改,工作量显的会很大,也不一定能够保证所有的label都能修改。下面给大家介绍一下使用runtime来一键改变UILabel上的字体:
1、在没有使用runtime进行修改字体之前的样式:
2、新建一个UILabel的Catagory:
3、具体实现代码:
#import "UILabel+ChangeFont.h"
#import
@implementation UILabel (ChangeFont)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class clLabel = [self class];
SEL originSelector = @selector(willMoveToSuperview:);
SEL swizzleSelector = @selector(wp_willMoveToSuperview:);
Method originMethod = class_getInstanceMethod(clLabel, originSelector);
Method swizzleMethod = class_getInstanceMethod(clLabel, swizzleSelector);
// 动态添加方法 实现是被交换的方法 还回值表示添加成功还是失败
BOOL addMethod = class_addMethod(clLabel, originSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
if (addMethod) {
//如果成功 说明类中不存在这个方法的实现
//将被交换方法的实现替换到这个并不存在的实现
class_replaceMethod(clLabel, swizzleSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
}else {
//否则交换两个方法的实现
method_exchangeImplementations(originMethod, swizzleMethod);
}
});
}
- (void)wp_willMoveToSuperview:(UIView *)newSuperview {
[self wp_willMoveToSuperview:newSuperview];
[self setFont:[UIFont systemFontOfSize:10]];
}
@end
4、之后效果如下:
如此便实现了全局的UILabel上字体的替换。