實際開發(fā)中可能面臨這樣的需求:
- 需要把所有的UILabel的字體放大2號
- 需要給所有ViewController添加友盟統(tǒng)計
簡單粗暴地方法就是UILabel和ViewController挨個改畦韭,但是作為一個程序員龄减,這樣改就太丟人了泞辐。就算不考慮自己的面子阻肿,也總得為公司的發(fā)展大計著想吧。
如果是項目開始,可以考慮建個BaseViewController轿亮,或者用Category也能實現⌒厍剑可是如果是項目已經有了一定規(guī)模之后我注,再提出以上需求,就需要用到更深層次的技術(runtime)了迟隅。
先是UILabel字體大小的問題但骨,新建一個UILabel的category
#import <UIKit/UIKit.h>
@interface UILabel (WFFontLabel)
@end
具體實現
#import "UILabel+WFFontLabel.h"
#import <objc/runtime.h>
@implementation UILabel (WFFontLabel)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
// 獲取兩個方法的IMP(指針)
Method originalMethod2 = class_getInstanceMethod(class, @selector(setFont:));
Method swizzledMethod2 = class_getInstanceMethod(class, @selector(WFSetFont:));
// 交換IMP
method_exchangeImplementations(originalMethod2, swizzledMethod2);
});
}
- (void)WFSetFont:(UIFont *)font {
UIFont * newFont = [UIFont systemFontOfSize:font.pointSize+10];
[self WFSetFont:newFont];
}
@end
當然,如果想更嚴謹一些智袭,可以寫成下面這樣(個人認為沒有必要)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
Method originalMethod2 = class_getInstanceMethod(class, @selector(setFont:));
Method swizzledMethod2 = class_getInstanceMethod(class, @selector(WFSetFont:));
BOOL didAddMethod2 = class_addMethod(class, @selector(setFont:), method_getImplementation(swizzledMethod2), method_getTypeEncoding(swizzledMethod2));
if (didAddMethod2) {
class_replaceMethod(class,
@selector(WFSetFont:),
method_getImplementation(originalMethod2),
method_getTypeEncoding(originalMethod2));
}else {
method_exchangeImplementations(originalMethod2, swizzledMethod2);
}
});
另外一個給所有ViewController添加友盟統(tǒng)計嗽冒,類似的,新建一個viewcontroller的category
#import <UIKit/UIKit.h>
@interface UIViewController (WFAnalysis)
@end
具體實現
#import "UIViewController+WFAnalysis.h"
#import <objc/message.h>
@implementation UIViewController (WFAnalysis)
+ (void)load {
[super load];
Method orgMethod = class_getInstanceMethod([self class], @selector(viewWillAppear:));
Method swizzledMethod = class_getInstanceMethod([self class], @selector(customViewWillAppear:));
method_exchangeImplementations(orgMethod, swizzledMethod);
}
- (void)customViewWillAppear:(BOOL)animated {
[self customViewWillAppear:animated];
NSLog(@"可以在這里添加統(tǒng)計代碼");
}
@end
原文地址:http://blog.csdn.net/zwf_apple/article/details/53127706