- runtime運行時用法之一 --- 交換類的方法,此處簡單寫了把系統(tǒng)的UIView的setBackgroundColor的方法換成了自定義的pb_setBackgroundColor
- 首先創(chuàng)建UIView的分類
- 在分類中導入頭文件#import <objc/runtime.h>
- 實現(xiàn)load類方法 --- 類被加載運行的時候就會調用
- 分別獲取系統(tǒng)setBackgroundColor方法 和自定義的 pb_setBackgroundColor 方法.然后交換
- 在AFNetworking中也有應用,AFN中利用runtime將訪問網絡的方法做了替換,替換后可以監(jiān)聽網絡連接狀態(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"
/** 導入頭文件 */
#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' 相當于調用系統(tǒng)的 'setBackgroundColor' 方法,原因是在load方法中進行了方法交換.
4. 注意:此處并沒有遞歸操作.
*/
[self pb_setBackgroundColor:[UIColor orangeColor]];
}
@end
- 控制器中測試
- 分別創(chuàng)建一個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];
}
-
效果如下: