美文网首页
runtime-方法交换-实例

runtime-方法交换-实例

作者: 淡眼云烟 | 来源:发表于2018-09-15 11:00 被阅读0次

需求:简单统一快速的给app里面所有的button修改字体颜色

#import "UIButton+NXButton.h"

@implementationUIButton (NXButton)

+ (void)load {

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        MethodcolorMethod =class_getInstanceMethod([selfclass],@selector(willMoveToSuperview:));

        MethodnewColorMethod =class_getInstanceMethod([selfclass],@selector(nx_willMoveToSuperview:));

        BOOLsuccess =class_addMethod([selfclass],@selector(willMoveToSuperview:),method_getImplementation(newColorMethod),method_getTypeEncoding(newColorMethod));

        if(success) {

      class_replaceMethod([selfclass],@selector(nx_willMoveToSuperview:),method_getImplementation(colorMethod),method_getTypeEncoding(colorMethod));

        }else{

            method_exchangeImplementations(colorMethod, newColorMethod);

        }

    });

}

- (void)nx_willMoveToSuperview:(UIView*)newSuperView {

    self.titleLabel.font = [UIFont systemFontOfSize:20];

    [self setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

}

@end

总结:

1.class_getInstanceMethod:得到类的实例方法

class_getClassMethod:得到类的类方法

2.class_addMethod:

OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp,

                                constchar*types)

    __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

cls 参数表示需要添加新方法的类;name 参数表示 selector 的方法名称(自己定义的方法);imp 即 implementation ,表示由编译器生成的、指向实现方法的指针。这个指针指向的方法就是我们新添加的方法;*types 表示我们要添加的方法的返回值和参数

相关文章

  • runtime-方法交换-实例

    需求:简单统一快速的给app里面所有的button修改字体颜色 #import "UIButton+NXButto...

  • Runtime-方法交换

    在iOS开发中,有一种编程方式叫面向切面编程(AOP),这种编程最大好处是,在不修改源代码的前提下,在原有功能上添...

  • Runtime-原理

    runtime初探对象与方法的本质runtime-消息发送runtime-动态方法解析runtime-消息转发 r...

  • iOS 方法交换

    交换类方法 交换实例方法

  • 无标题文章

    //静态就交换静态,实例方法就交换实例方法void Swizzle(Class c, SEL origSEL, S...

  • runtime 应用

    1. 交换方法 1.1 获取类方法 1.2 获取实例方法 1.3 交换两个方法 实例: 2. 分类添加属性 下面给...

  • Runtime应用

    实例一 创建类 实例二 编码解码 实例三 方法交换

  • ios 交换方法

    1.类/分类添加方法后交换 结果: 2.创建并交换实例方法 结果: 3.创建并交换类方法 结果:

  • Runtime

    runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)2:通过runti...

  • Day3

    1 runtime运行时机制1:通过runtime,实现方法交换(交换两个类方法、交换两个实例方法)。2:通过ru...

网友评论

      本文标题:runtime-方法交换-实例

      本文链接:https://www.haomeiwen.com/subject/zvpzgftx.html