美文网首页
ios - runtime运行时应用---交换方法

ios - runtime运行时应用---交换方法

作者: 皮皮瑞 | 来源:发表于2017-04-06 20:54 被阅读0次

    runtime运行时用法之一 --- 交换类的方法,此处简单写了把系统的UIView的setBackgroundColor的方法换成了自定义的pb_setBackgroundColor

    首先创建UIView的分类

    在分类中导入头文件#import

    实现load类方法 --- 类被加载运行的时候就会调用

    分别获取系统setBackgroundColor方法 和自定义的 pb_setBackgroundColor 方法.然后交换

    在AFNetworking中也有应用,AFN中利用runtime将访问网络的方法做了替换,替换后可以监听网络连接状态

    staticinlinevoidaf_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector){    Method originalMethod = class_getInstanceMethod(theClass, originalSelector);    Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);    method_exchangeImplementations(originalMethod, swizzledMethod);

    #import"UIView+BlackView.h"/** 导入头文件 */#import@implementationUIView(BlackView)+(void)load{/** 获取原始setBackgroundColor方法 */Method originalM = class_getInstanceMethod([selfclass],@selector(setBackgroundColor:));/** 获取自定义的pb_setBackgroundColor方法 */Method exchangeM = class_getInstanceMethod([selfclass],@selector(pb_setBackgroundColor:));/** 交换方法 */method_exchangeImplementations(originalM, exchangeM);}/** 自定义的方法 */-(void)pb_setBackgroundColor:(UIColor*) color{NSLog(@"%s",__FUNCTION__);/**

    1.更改颜色

    2.所有继承自UIView的控件,设置背景色都会设置成自定义的'orangeColor'

    3. 此时调用的方法 'pb_setBackgroundColor' 相当于调用系统的 'setBackgroundColor' 方法,原因是在load方法中进行了方法交换.

    4. 注意:此处并没有递归操作.

    */[selfpb_setBackgroundColor:[UIColororangeColor]];}@end

    控制器中测试

    分别创建一个Button 以及一个 View 并且设置好颜色,看效果

    - (void)viewDidLoad {    [superviewDidLoad];UIButton* btn = [UIButtonnew];    btn.backgroundColor = [UIColorblackColor];    [self.view addSubview:btn];    btn.frame =CGRectMake(0,30,200,40);    [btn setTitle:@"点击"forState:UIControlStateNormal];UIView* viw = [[UIViewalloc] initWithFrame:CGRectMake(0,100,100,100)];    viw.backgroundColor = [UIColorblueColor];    [self.view addSubview:viw];    }

    效果如下:

    相关文章

      网友评论

          本文标题:ios - runtime运行时应用---交换方法

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