美文网首页
Runtime交换方法

Runtime交换方法

作者: CowboyBebop | 来源:发表于2016-07-27 10:14 被阅读41次

利用Runtime 替换系统的方法,从而实现修改全局view的背景色。

####### 注:好多第三方的类库,都是导入头文件,不需要写其他的代码就可以完成一些设置,其实他的思路就是,重写load方法,然后利用Runtime 替换系统方法。下面是FDFullscreenPopGesture的load方法:
+ (void)load{
//线程保证下面的代码只会走一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
//定义系统的视图将要出现的方法名。
SEL originalSelector = @selector(viewWillAppear:);
//定义一个自定义的视图将要出现的方法名
SEL swizzledSelector = @selector(fd_viewWillAppear:);
//class_getInstanceMethod :class根据后面的方法名获取对象方法,class_getClassMethod:是根据方法名获取类方法

    Method originalMethod = class_getInstanceMethod(class, originalSelector);
//获取到的系统的视图将要出现的方法。
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
//自定义的视图将要出现的方法
    
    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
//给类添加方法,方法名是:originalSelector,方法的实现:method_getImplementation(swizzledMethod)
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
//如果添加成功就替换掉系统方法originalMethod的实现函数
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
//失败就交换两个方法的实现。
    }
});
//其实主要目的就是替换掉原始方法:originalMethod的实现函数。
1,新建UIView的分类,首先导入<obj/message.h>类库,在load方法里直接替换UIview 的系统设置背景色的方法,替换为自己的方法。
+(void)load{

//    class_getInstanceMethod  获取对象方法

//    class_getMethodImplementation 获取方法的实现

//    class_getClassMethod 获取类方法

Method  bgMethod = class_getInstanceMethod([UIView class],   @selector(setBackgroundColor:));

Method zdq_bgMethod = class_getInstanceMethod([UIView class], @selector(zdq_backgroundColor:));

//交换方法

method_exchangeImplementations(bgMethod, zdq_bgMethod);

}

2,自己定义设置背景色的方法。(这里颜色是写死的)
-(void)zdq_backgroundColor:(UIColor *)color{
//这里如果调用系统的setBackgroundColor方法,才会真正实现循环调用
[self zdq_backgroundColor:[UIColor whiteColor]];

}

相关文章

  • runtime

    runtime交换方法 动态添加方法

  • runTime常用方法

    使用runTime改变实例成员的值 使用runtime来交换两个方法 注意再次调用该方法不交换 使用runTime...

  • Runtime

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

  • Day3

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

  • runtime的理解(二)

    主要内容 利用 runtime 交换方法 利用 runtime 动态添加方法 利用 runtime 动态添加属性 ...

  • 查看SDK调用支付宝参数

    使用runtime 方法交换openurl

  • objc runtime (四)动态添加属性

    在《objc runtime (二)交换方法》中我提到过runtime最实用的就是交换方法和动态添加属性两个用法。...

  • iOS runtime如何交换两个类方法

    如有转载,请标明出处:iOS runtime如何交换两个类方法 runtime交换实例方法,老生常谈的问题,很多b...

  • iOS -- runtime的应用

    runtime主要有一下几种应用场景 方法交换 添加属性 (一)方法交换 (1)字体适配 方法交换实际交换的是方法...

  • runtime和oc内存区域(2018-04-02)

    runtime常用的几个方法: 交换方法 动态添加属性 动态添加方法 1.交换方法 class_getClassM...

网友评论

      本文标题:Runtime交换方法

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