runtime-方法交換-實例

需求:簡單統(tǒng)一快速的給app里面所有的button修改字體顏色

#import "UIButton+NXButton.h"

@implementationUIButton (NXButton)

+ (void)load {

? ? staticdispatch_once_tonceToken;

? ? dispatch_once(&onceToken, ^{

? ? ? ? MethodcolorMethod =class_getInstanceMethod([selfclass],@selector(willMoveToSuperview:));

? ? ? ? MethodnewColorMethod =class_getInstanceMethod([selfclass],@selector(nx_willMoveToSuperview:));

? ? ? ? BOOLsuccess =class_addMethod([selfclass],@selector(willMoveToSuperview:),method_getImplementation(newColorMethod),method_getTypeEncoding(newColorMethod));

? ? ? ? if(success) {

? ? ? class_replaceMethod([selfclass],@selector(nx_willMoveToSuperview:),method_getImplementation(colorMethod),method_getTypeEncoding(colorMethod));

? ? ? ? }else{

? ? ? ? ? ? method_exchangeImplementations(colorMethod, newColorMethod);

? ? ? ? }

? ? });

}

- (void)nx_willMoveToSuperview:(UIView*)newSuperView {

? ? self.titleLabel.font = [UIFont systemFontOfSize:20];

? ? [self setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];

}

@end

總結:

1.class_getInstanceMethod:得到類的實例方法

class_getClassMethod:得到類的類方法

2.class_addMethod:

OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp,

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? constchar*types)

? ? __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

cls 參數表示需要添加新方法的類;name 參數表示 selector 的方法名稱(自己定義的方法);imp 即 implementation ,表示由編譯器生成的、指向實現方法的指針。這個指針指向的方法就是我們新添加的方法;*types 表示我們要添加的方法的返回值和參數

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 轉載:http://yulingtianxia.com/blog/2014/11/05/objective-c-r...
    F麥子閱讀 839評論 0 2
  • 轉載:http://www.cocoachina.com/ios/20161102/17920.html 因為Ob...
    F麥子閱讀 703評論 0 1
  • 轉至元數據結尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉至元數據起始第一章:isa和Class一....
    40c0490e5268閱讀 2,072評論 0 9
  • 本文轉載自:http://yulingtianxia.com/blog/2014/11/05/objective-...
    ant_flex閱讀 888評論 0 1
  • 文中的實驗代碼我放在了這個項目中。 以下內容是我通過整理[這篇博客] (http://yulingtianxia....
    茗涙閱讀 1,028評論 0 6

友情鏈接更多精彩內容