经常会遇到重复点击某个按钮 事件被响应多次的情景, 有时候可能对程序本身并没有什么影响 , 可有时候偏偏需要限制button响应事件直接的间隔 .
方法一 : 标记
1 . 利用空闲enable属性来标记
- (IBAction)clickBtn1:(UIbutton *)sender
{
sender.enabled = NO;
doSomething
sender.enabled = YES;
}
2. 专门定义一个属性标记
- (IBAction)clickBtn1:(UIbutton *)sender
{
if (doingSomeThing) return;
doingSomeThing = YES;
doSomething
doingSomeThing = NO;
}
方法二 : 利用runtime来实现
和前一种方法的实现原理基本一样 只不过通过给UIControl 添加分类 由此扩大了应用范围
首先给按钮条件一个属性 记录目标间隔时间
@interface UIControl (MYButton)
@property (nonatomic, assign) NSTimeInterval my_acceptEventInterval; // 可以用这个给重复点击加间隔
@end
static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";
- (NSTimeInterval)my_acceptEventInterval
{
return [objc_getAssociatedObject(self, UIControl_acceptEventInterval) doubleValue];
}
- (void)setMy_acceptEventInterval:(NSTimeInterval)my_acceptEventInterval
{
objc_setAssociatedObject(self, UIControl_acceptEventInterval, @(my_acceptEventInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
//交换系统的方法
@implementation UIControl (MYButton)
+ (void)load
{
Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method b = class_getInstanceMethod(self, @selector(__my_sendAction:to:forEvent:));
method_exchangeImplementations(a, b);
}
@end
//定义自己的点击事件
- (void)__my_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
if (self.my_ignoreEvent) return;
if (self.my_acceptEventInterval > )
{
self.my_ignoreEvent = YES;
[self performSelector:@selector(setMy_ignoreEvent:) withObject:@(NO) afterDelay:self.my_acceptEventInterval];
}
[self __my_sendAction:action to:target forEvent:event];
}
实际使用起来就是这个样子
UIButton *tempBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[tempBtn addTarget:self action:@selector(clickWithInterval:) forControlEvents:UIControlEventTouchUpInside];
tempBtn.uxy_acceptEventInterval = 0.5;
一个应用Runtime 的小小实例