runtime运行时修改字体

前言

最近遇到一个需求,要改掉app的字体,一个一个改不太现实,由于一直用的系统字体,于是就想到了用运行时来修改字体(仅限于纯代码的APP),闲话少说,直接上代码。

  • 方法交换

首先创建一个UIfontcategory,把自己写的代码放在category里面(方法交换要写到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:));
这句代码是通过运行时获取自己写的方法,然后获取系统方法Method systemFontSize = class_getClassMethod(self, @selector(systemFontOfSize:));
最后进行方法交换
method_exchangeImplementations(myFontSize, systemFontSize);

  • 方法使用

下面是控制器里的代码,也就是创建的标签控制器

@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 = @"代码标签";
    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

运行以后的截图


Simulator Screen Shot

通过运行时来改变系统的字体,仅适用于纯代码写的Label,xib拖拽的控件不起作用,需要手动调用一下系统的方法systemFontSize:才能起作用,例如xib标签1的字体改变了,而xib标签2的字体没有改变,因为xib标签1调用了一下systemFontSize:方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转至元数据结尾创建: 董潇伟,最新修改于: 十二月 23, 2016 转至元数据起始第一章:isa和Class一....
    40c0490e5268阅读 5,865评论 0 9
  • 因为要结局swift3.0中引用snapKit的问题,看到一篇介绍Xcode8,swift3变化的文章,觉得很详细...
    uniapp阅读 10,075评论 0 12
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,798评论 19 139
  • 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的转载 这篇文章完全是基于南峰子老师博客的...
    西木阅读 30,723评论 33 466
  • 简单自述下: 本人前端开发者,深圳一公司在职员工,非出自前端科班,乃自学前端已近两年之久。 受前端大牛们的刺激,了...
    小兴nice阅读 3,909评论 15 1