iOS runtime之--动态修改字体大小

1,681 阅读4分钟

本文版权归公众号【一个老码农】所有。

上篇文章我们大概了解一下runtime的作用,本篇文章我介绍一下runtime的实际应用场景之一:怎样利用runtime的方法交换,在不修改原有代码的基础上动态的根据屏幕尺寸修改字体大小,包括xibstoryboard中拖的控件。

我们知道,通常代码设置字体大小用的是UIFont的几个类方法 :

systemFontOfSize

fontWithName:size

boldSystemFontOfSize

italicSystemFontOfSize

...

那么既然runtime可以进行方法交换,我们只要自定义一个方法,替换系统的方法不就可以实现了吗?话不多说,我们开始动手

实现NSObject类方法交换

创建NSObject分类,并增加一个可进行“Method交换”的方法。Method交换的本质,其实就是imp指针的交换。系统给我们提供了一个C语言的函数method_exchangeImplementations可以进行交换。流程如下:

1.根据原方法和目标方法的selector,获取方法的method。如果是类方法用class_getClassMethod获取method,如是对象方法则用class_getInstanceMethod获取method

2.获取到method后,调用method_exchangeImplementations函数进行两个method的imp指针的交换

#import "NSObject+Category.h"
#import <objc/runtime.h>

@implementation NSObject (Category)

/**
 @brief 方法替换
 @param originselector 替换的原方法
 @param swizzleSelector 替换后的方法
 @param isClassMethod 是否为类方法,YES为类方法,NO为对象方法
 */
+ (void)runtimeReplaceFunctionWithSelector:(SEL)originselector
                           swizzleSelector:(SEL)swizzleSelector
                             isClassMethod:(BOOL)isClassMethod
{
    Method originMethod;
    Method swizzleMethod;
    if (isClassMethod == YES) {
        originMethod = class_getClassMethod([self class], originselector);
        swizzleMethod = class_getClassMethod([self class], swizzleSelector);
    }else{
        originMethod = class_getInstanceMethod([self class], originselector);
        swizzleMethod = class_getInstanceMethod([self class], swizzleSelector);
    }
    method_exchangeImplementations(originMethod, swizzleMethod);
}
@end

UIFont设置font的类方法替换

新建一个UIFont分类,在+(void)load方法中进行UIFont系统方法的替换

#import "UIFont+Category.h"
#import "NSObject+Category.h"

@implementation UIFont (Category)

//+(void)load方法会在main函数之前自动调用,不需要手动调用
+ (void)load
{
    //交换systemFontOfSize: 方法
    [[self class] runtimeReplaceFunctionWithSelector:@selector(systemFontOfSize:) swizzleSelector:@selector(customSystemFontOfSize:) isClassMethod:YES];
    //交换fontWithName:size:方法
    [[self class] runtimeReplaceFunctionWithSelector:@selector(fontWithName:size:) swizzleSelector:@selector(customFontWithName:size:) isClassMethod:YES];
}

//自定义的交换方法
+ (UIFont *)customSystemFontOfSize:(CGFloat)fontSize
{
    CGFloat size = [UIFont transSizeWithFontSize:fontSize];
    ///这里并不会引起递归,方法交换后,此时调用customSystemFontOfSize方法,其实是调用了原来的systemFontOfSize方法
    return [UIFont customSystemFontOfSize:size];
}

//自定义的交换方法
+ (UIFont *)customFontWithName:(NSString *)fontName size:(CGFloat)fontSize
{
    CGFloat size = [UIFont transSizeWithFontSize:fontSize];
    return [UIFont customFontWithName:fontName size:size];
}

///屏幕宽度大于320的,字体加10。(此处可根据不同的需求设置字体大小)
+ (CGFloat)transSizeWithFontSize:(CGFloat)fontSize
{
    CGFloat size = fontSize;
    CGFloat width = [UIFont getWidth];
    if (width > 320) {
        size += 10;
    }
    return size;
}

///获取竖屏状态下的屏幕宽度
+ (CGFloat)getWidth
{
    for (UIScreen *windowsScenes in UIApplication.sharedApplication.connectedScenes) {
        UIWindowScene * scenes = (UIWindowScene *)windowsScenes;
        UIWindow *window = scenes.windows.firstObject;
        if (scenes.interfaceOrientation == UIInterfaceOrientationPortrait) {
            return window.frame.size.width;
        }
        return window.frame.size.height;
    }
    return 0;
}

@end

至此就实现了,动态改变字体大小的目的,那xibstoryboard拖的控件怎么修改呢?我们接着看

动态修改xib和storyboard控件的字体大小

xib和sb拖拽的控件,都会调用 initWithCoder方法,那么我们可以自定义一个方法,替换掉initWithCoder,并在此方法中修改控件的字体不就可以了吗。我们先用UILabel举例,先创建一个UILabel的分类,然后在+(void)load方法中进行initWithCoder方法的交换

#import "UILabel+Category.h"
#import "NSObject+Category.h"

@implementation UILabel (Category)

+ (void)load
{
    [[self class] runtimeReplaceFunctionWithSelector:@selector(initWithCoder:) swizzleSelector:@selector(customInitWithCoder:) isClassMethod:NO];
}

- (instancetype)customInitWithCoder:(NSCoder *)coder
{
    if ([self customInitWithCoder:coder]) {
        ///此时调用fontWithName:size:方法,实际上调用的是方法交换后的customFontWithName:size:
        self.font = [UIFont fontWithName:self.font.familyName size:self.font.pointSize];
    }
    return self;
}

@end

此时我们就实现了,UILabel字体大小的动态修改,同理我们实现其它几个开发中常用的几个控件修改

UIButton的分类

#import "UIButton+Category.h"
#import "NSObject+Category.h"

@implementation UIButton (Category)

+ (void)load
{
    [[self class] runtimeReplaceFunctionWithSelector:@selector(initWithCoder:) swizzleSelector:@selector(customInitWithCoder:) isClassMethod:NO];
}

- (instancetype)customInitWithCoder:(NSCoder *)coder
{
    if ([self customInitWithCoder:coder]) {
        if (self.titleLabel != nil) {
            self.titleLabel.font = [UIFont fontWithName:self.titleLabel.font.familyName size:self.titleLabel.font.pointSize];
        }
    }
    return self;
}

@end

UITextField的分类

#import "UITextField+Category.h"
#import "NSObject+Category.h"

@implementation UITextField (Category)

+ (void)load
{
    [[self class] runtimeReplaceFunctionWithSelector:@selector(initWithCoder:) swizzleSelector:@selector(customInitWithCoder:) isClassMethod:NO];
}

- (instancetype)customInitWithCoder:(NSCoder *)coder
{
    if ([self customInitWithCoder:coder]) {
        self.font = [UIFont fontWithName:self.font.familyName size:self.font.pointSize];
    }
    return self;
}

@end

UITextView的分类

#import "UITextView+Category.h"
#import "NSObject+Category.h"

@implementation UITextView (Category)

+ (void)load
{
    [[self class] runtimeReplaceFunctionWithSelector:@selector(initWithCoder:) swizzleSelector:@selector(customInitWithCoder:) isClassMethod:NO];
}

- (instancetype)customInitWithCoder:(NSCoder *)coder
{
    if ([self customInitWithCoder:coder]) {
        self.font = [UIFont fontWithName:self.font.familyName size:self.font.pointSize];
    }
    return self;
}

@end

到此,我们就完成了控件字体大小的动态修改,我们在storyboard中拖几个控件,然后用代码创建几个控件,分别看一下修改前和修改后的效果

设置前 设置后

注:Swift语言做法类似,但是Swift不允许重写+(void)load方法。所以如果是Swift,文中的+ (void)load需要改为自己定义的方法,并在AppDelegatedidFinishLaunchingWithOptions方法中进行调用。

出自公众号:【一个老码农】,关注公众号免费获取学习视频

原文链接:runtime之--动态修改字体大小