我们平时在写代码的时候,很少关注按钮重复点击的问题。这往往会导致程序的bug,轻则重复弹出页面,重则多次提交网络请求,导致app crash掉。
可以采用rumtime解决这个问题。
代码如下:
1、创建UIButton的分类
UIButton+OnceButton.h
#import <UIKit/UIKit.h> @interface UIButton (OnceButton) - (void)setT_acceptEventInterval:(NSTimeInterval)uxy_acceptEventInterval; @end
UIButton+OnceButton.m
#import "UIButton+OnceButton.h" #import <objc/runtime.h> @interface UIControl (OnceButton) @property (nonatomic, assign) NSTimeInterval t_acceptEventInterval; @property (nonatomic) BOOL t_ignoreEvent; @end static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval"; static const char *aaa = "abc"; @implementation UIControl (OnceButton) @dynamic t_ignoreEvent; - (NSTimeInterval)t_acceptEventInterval { return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue]; } - (void)setT_acceptEventInterval:(NSTimeInterval)uxy_acceptEventInterval { objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(uxy_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (BOOL)t_ignoreEvent { return [objc_getAssociatedObject(self, aaa) boolValue]; } - (void)setT_ignoreEvent:(BOOL)ignore { objc_setAssociatedObject(self, aaa, @(ignore), OBJC_ASSOCIATION_RETAIN_NONATOMIC); } + (void)load{ Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:)); Method b = class_getInstanceMethod(self, @selector(__t_sendAction:to:forEvent:)); method_exchangeImplementations(a, b); } - (void)__t_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event { if (self.t_ignoreEvent) return; if (self.t_acceptEventInterval > 0) { self.t_ignoreEvent = YES; [self performSelector:@selector(setT_ignoreEvent:) withObject:@(NO) afterDelay:self.t_acceptEventInterval]; self.backgroundColor = [UIColor greenColor]; } [self __t_sendAction:action to:target forEvent:event]; }
2、然后在ViewContrller.m里面这样调用
#import "ViewController.h" #import "UIButton+OnceButton.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [tempBtn setFrame:CGRectMake(100, 100, 120, 30)]; [tempBtn setBackgroundColor:[UIColor redColor]]; [tempBtn addTarget:self action:@selector(clickWithInterval:) forControlEvents:UIControlEventTouchUpInside]; [tempBtn setT_acceptEventInterval:6]; [self.view addSubview:tempBtn]; } - (void)clickWithInterval:(UIButton *)sender{ NSLog(@"6s后可以执行"); }