iOS 动态改变字体

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wjy0629/article/details/81258312

方法1:一次改变,利用Runtime进行处理,对UILabel写一个Category

方法2:动态改变,当设置字体后,当前已创建的均需要改变,通知

//
//  UILabel+ChangeFont.m
//  ChangeFont
//
//  Created by Danale on 2018/7/28.
//  Copyright © 2018年 wjy. All rights reserved.
//

#import "UILabel+ChangeFont.h"
#import <objc/runtime.h>
NSString * const FONT_NAME_KEY = @"wadefsdgrfhtdgjyfhkgl";
@implementation UILabel (ChangeFont)
/****************************************       动态改变        *****************************************/
-(instancetype)init
{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeFont) name:FONT_NAME_KEY object:nil];
    }
    return self;
}
-(void)changeFont
{
    NSString * currentFont = [[NSUserDefaults standardUserDefaults]objectForKey:FONT_NAME_KEY];
    self.font = [UIFont fontWithName:currentFont size:50];
}
- (void)awakeFromNib
{
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeFont) name:FONT_NAME_KEY object:nil];
}



/****************************************       1次改变       *****************************************/
+(void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL sysSel = @selector(willMoveToSuperview:);
        SEL mySel = @selector(myWillMoveToSuperView:);
        Method sysM = class_getInstanceMethod([self class], sysSel);
        Method myM = class_getInstanceMethod([self class], mySel);
        BOOL add = class_addMethod(self, sysSel, method_getImplementation(myM), method_getTypeEncoding(myM));
        if (add) {
            class_replaceMethod(self, mySel, method_getImplementation(sysM), method_getTypeEncoding(sysM));
        }else{
            method_exchangeImplementations(sysM, myM);
        }
    });
}
-(void)myWillMoveToSuperView:(UIView *)superView
{
    NSLog(@"superView----%@",superView.class);
    [self myWillMoveToSuperView:superView];
    NSString * currentFont = [[NSUserDefaults standardUserDefaults]objectForKey:FONT_NAME_KEY];
    if (self && currentFont.length) {
        self.font = [UIFont fontWithName:currentFont size:50];
    }
}
@end

猜你喜欢

转载自blog.csdn.net/wjy0629/article/details/81258312