1. 程式人生 > >利用Runtime來攔截UIButton的點選事件,防止重複點選

利用Runtime來攔截UIButton的點選事件,防止重複點選

對於公司原來的一些程式碼,想對UIButton的點選事件做一部分修改,但是如果使用繼承出來的UIBtton來解決的話, 又要改大量的程式碼,這時候,使用runtime攔截替換髮送點選事件的方法可以迅速解決這個問題,超級給力!

不廢話,直接上程式碼

#import <UIKit/UIKit.h>

@interface UIControl (UIControl_XY)
@property (nonatomic, assign) NSTimeInterval cjr_acceptEventInterval;// 可以用這個給重複點選加間隔
@end

#import "UIControl+UIControl_XY.h"
#import <objc/runtime.h> @interface UIControl() @property (nonatomic, assign) NSTimeInterval cjr_acceptEventTime; @end @implementation UIControl (UIControl_XY) static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval"; static const char *UIControl_acceptEventTime = "UIControl_acceptEventTime"
; - (NSTimeInterval )cjr_acceptEventInterval{ return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue]; } - (void)setCjr_acceptEventInterval:(NSTimeInterval)cjr_acceptEventInterval{ objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(cjr_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (NSTimeInterval
)cjr_acceptEventTime{ return [objc_getAssociatedObject(self, UIControl_acceptEventTime) doubleValue]; } - (void)setCjr_acceptEventTime:(NSTimeInterval)cjr_acceptEventTime{ objc_setAssociatedObject(self, UIControl_acceptEventTime, @(cjr_acceptEventTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } + (void)load{ //獲取著兩個方法 Method systemMethod = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:)); SEL sysSEL = @selector(sendAction:to:forEvent:); Method myMethod = class_getInstanceMethod(self, @selector(cjr_sendAction:to:forEvent:)); SEL mySEL = @selector(cjr_sendAction:to:forEvent:); //新增方法進去 BOOL didAddMethod = class_addMethod(self, sysSEL, method_getImplementation(myMethod), method_getTypeEncoding(myMethod)); //如果方法已經存在了 if (didAddMethod) { class_replaceMethod(self, mySEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod)); }else{ method_exchangeImplementations(systemMethod, myMethod); } //----------------以上主要是實現兩個方法的互換,load是gcd的只shareinstance,果斷保證執行一次 } - (void)cjr_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event{ if (NSDate.date.timeIntervalSince1970 - self.cjr_acceptEventTime < self.cjr_acceptEventInterval) { return; } if (self.cjr_acceptEventInterval > 0) { self.cjr_acceptEventTime = NSDate.date.timeIntervalSince1970; } [self cjr_sendAction:action to:target forEvent:event]; } @end
@interface ALViewController ()
@property (nonatomic, strong) UIButton *;
@end

@implementation AutoLayoutViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.suggessBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.suggessBtn addTarget:self action:@selector(clickWithInterval:) forControlEvents:UIControlEventTouchUpInside];
    self.suggessBtn.cjr_acceptEventInterval = 5.0f;
}

- (void)clickWithInterval:(UIButton *)suButton{
    NSLog(@"打印出來--"):
}