OC基础资源整理iOS开发常用

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

2016-05-06  本文已影响4965人  AlexPei
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



- (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];
    

}


上一篇下一篇

猜你喜欢

热点阅读