- runtime運(yùn)行時(shí)用法之一 --- 交換類的方法,此處簡(jiǎn)單寫了把系統(tǒng)的UIView的setBackgroundColor的方法換成了自定義的pb_setBackgroundColor
- 首先創(chuàng)建UIView的分類
- 在分類中導(dǎo)入頭文件#import <objc/runtime.h>
- 實(shí)現(xiàn)load類方法 --- 類被加載運(yùn)行的時(shí)候就會(huì)調(diào)用
- 分別獲取系統(tǒng)setBackgroundColor方法 和自定義的 pb_setBackgroundColor 方法.然后交換
- 在AFNetworking中也有應(yīng)用,AFN中利用runtime將訪問(wèn)網(wǎng)絡(luò)的方法做了替換,替換后可以監(jiān)聽(tīng)網(wǎng)絡(luò)連接狀態(tài)
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"
/** 導(dǎo)入頭文件 */
#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的控件,設(shè)置背景色都會(huì)設(shè)置成自定義的'orangeColor'
3. 此時(shí)調(diào)用的方法 'pb_setBackgroundColor' 相當(dāng)于調(diào)用系統(tǒng)的 'setBackgroundColor' 方法,原因是在load方法中進(jìn)行了方法交換.
4. 注意:此處并沒(méi)有遞歸操作.
*/
[self pb_setBackgroundColor:[UIColor orangeColor]];
}
@end
- 控制器中測(cè)試
- 分別創(chuàng)建一個(gè)Button 以及一個(gè) View 并且設(shè)置好顏色,看效果
- (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:@"點(diǎn)擊" forState:UIControlStateNormal];
UIView * viw = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];
viw.backgroundColor = [UIColor blueColor];
[self.view addSubview:viw];
}
-
效果如下: