需求:簡單統(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 表示我們要添加的方法的返回值和參數