button的重复点击问题
简单的办法 利用enable属性来标记
1 - (IBAction)clickBtn1:(UIbutton *)sender 2 { 3 sender.enabled = NO; 4 doSomething 5 sender.enabled = YES; 6 }
或者定义一个属性标记
1 - (IBAction)clickBtn1:(UIbutton *)sender 2 { 3 if (doingSomeThing) return; 4 doingSomeThing = YES; 5 doSomething 6 doingSomeThing = NO; 7 }
在time时间内不论调用多少次,只执行一次。
利用runtime 实现
首先给按钮条件一个属性 记录目标间隔时间
1 @interface UIControl (MYButton) 2 @property (nonatomic, assign) NSTimeInterval my_acceptEventInterval; // 可以用这个给重复点击加间隔 3 @end 4 static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval"; 5 - (NSTimeInterval)my_acceptEventInterval 6 { 7 return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue]; 8 } 9 - (void)setMy_acceptEventInterval:(NSTimeInterval)my_acceptEventInterval 10 { 11 objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(my_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC); 12 }
//交换系统的方法
1 @implementation UIControl (MYButton) 2 + (void)load 3 { 4 Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:)); 5 Method b = class_getInstanceMethod(self, @selector(__my_sendAction:to:forEvent:)); 6 method_exchangeImplementations(a, b); 7 } 8 @end
//定义自己的点击事件
1 - (void)__my_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event 2 { 3 if (self.my_ignoreEvent) return; 4 if (self.my_acceptEventInterval > 0) 5 { 6 self.my_ignoreEvent = YES; 7 [self performSelector:@selector(setMy_ignoreEvent:) withObject:@(NO) afterDelay:self.my_acceptEventInterval]; 8 } 9 [self __my_sendAction:action to:target forEvent:event]; 10 }
实际使用起来就是这个样子
1 UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 2 [tempBtn addTarget:self action:@selector(clickWithInterval:) forControlEvents:UIControlEventTouchUpInside]; 3 tempBtn.uxy_acceptEventInterval = 0.5;
- (void)addaction{
nsobject cancelPerfromSelector....
self performselector@(doSometing)... afterdeley:5..
}
- (void)doSomething{
你真正做得事情。。。
...
}
这种,在5秒内,你重复点击不会生效。只有最后一次才会