標籤:
#import "UIViewController+Parents.h"
/** 匯入標頭檔 */
#import <objc/runtime.h>
@implementation UIViewController (Parents)
//load方法會在類第一次載入的時候被調用
//調用的時間比較靠前,適合在這個方法裡做方法交換
+ (void)load{
//方法交換應該被保證,在程式中只會執行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//獲得viewController的生命週期方法的selector
SEL systemSel = @selector(viewDidDisappear:);
//自己實現的將要被交換的方法的selector
SEL swizzSel = @selector(swiz_viewDidDisappear:);
//兩個方法的Method
Method systemMethod = class_getInstanceMethod([self class], systemSel);
Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
//首先動態添加方法,實現是被交換的方法,傳回值表示添加成功還是失敗
BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
if (isAdd) {
//如果成功,說明類中不存在這個方法的實現
//將被交換方法的實現替換到這個並不存在的實現
class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
}else{
//否則,交換兩個方法的實現
method_exchangeImplementations(systemMethod, swizzMethod);
}
});
}
- (void)swiz_viewDidDisappear:(BOOL)animated{
//這時候調用自己,看起來像是死迴圈
//但是其實自己的實現已經被替換了
[self swiz_viewDidDisappear:animated];
[self setExclusiveTouchForButtons:self.view];
NSLog(@"swizzle");
}
-(void)setExclusiveTouchForButtons:(UIView *)myView
{
for (UIView * v in [myView subviews]) {
if([v isKindOfClass:[UIButton class]])
[((UIButton *)v) setExclusiveTouch:YES];
else if ([v isKindOfClass:[UIView class]]){
[self setExclusiveTouchForButtons:v];
}
}
}
iOS 利用運行時交換系統方法實現禁止同時點擊兩個按鈕觸發多個事件