zoukankan      html  css  js  c++  java
  • ios

    • runtime运行时用法之一 --- 交换类的方法,此处简单写了把系统的UIView的setBackgroundColor的方法换成了自定义的pb_setBackgroundColor
    • 首先创建UIView的分类
    • 在分类中导入头文件#import <objc/runtime.h>
    • 实现load类方法 --- 类被加载运行的时候就会调用
    • 分别获取系统setBackgroundColor方法 和自定义的 pb_setBackgroundColor 方法.然后交换
    • 在AFNetworking中也有应用,AFN中利用runtime将访问网络的方法做了替换,替换后可以监听网络连接状态
    static inline void af_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 <objc/runtime.h>
    
    
    @implementation UIView (BlackView)
    
    
    
    +(void)load{
    
        /** 获取原始setBackgroundColor方法 */
        Method originalM = class_getInstanceMethod([self class], @selector(setBackgroundColor:));
        
        /** 获取自定义的pb_setBackgroundColor方法 */
        Method exchangeM = class_getInstanceMethod([self class], @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. 注意:此处并没有递归操作.
         */
        [self pb_setBackgroundColor:[UIColor orangeColor]];
    }
    
    @end
    
    
    
    • 控制器中测试
    • 分别创建一个Button 以及一个 View 并且设置好颜色,看效果
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIButton * btn = [UIButton new];
        btn.backgroundColor = [UIColor blackColor];
        [self.view addSubview:btn];
        btn.frame = CGRectMake(0, 30, 200, 40);
        [btn setTitle:@"点击" forState:UIControlStateNormal];
        
        UIView * viw = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
        viw.backgroundColor = [UIColor blueColor];
        [self.view addSubview:viw];
        
    
    }
    
    
    
    • 效果如下:
  • 相关阅读:
    【Python3爬虫】一次应对JS反调试的记录
    【Python3爬虫】突破反爬之应对前端反调试手段
    学习CSS之如何改变CSS伪元素的样式
    学习CSS之用CSS实现时钟效果
    学习CSS之用CSS绘制一些基本图形
    【Python3爬虫】一次破解JS加密数据的记录
    Linux安装部署Redis(超级详细)
    Linux部署MongoDB
    使用Nginx对.NetCore站点进行反向代理
    Linux部署.NetCore站点 使用Supervisor进行托管部署
  • 原文地址:https://www.cnblogs.com/adampei-bobo/p/5463964.html
Copyright © 2011-2022 走看看