1. 程式人生 > >iOS 動態改變字型

iOS 動態改變字型

方法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