ios - runtime運行時應用---交換方法


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

}


  • 效果如下:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM