UIButton重复点击,重复触发,怎么办
2015-10-08 本文已影响2342人
TEASON
支持原创,如需转载, 请注明出处@TEASON
UIButton重复点击,重复触发,针对这些暴力调试,不能让方法无限制的触发。
我寻找了很多人的解决方案, 把一些常用的介绍出来 .
1.设开关. (定时)
请求是异步操作时,可以在调用前enable关闭。等DidFinished后再enable打开。所以过程中按钮是不能点的。
当然也可以控制UIbutton自带的select属性,范例如下:
- (void) btnDone:(UIButton*)btn
{
if(btn.selected) return;
btn.selected = YES;
[self performSelector:@selector(doSth) withObject:nil afterDelay:0.5]; //使用延时进行限制。
//to do something.
}
- (void)doSth
{
UIButton *btn=(UIButton*)[self.view viewWithTag:33];
btn.selected=NO;
[timer invalidate];
timer=nil;
}
2.NSDelayedPerforming
/**************** Delayed perform ******************/
@interface NSObject (NSDelayedPerforming)
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray<NSString *> *)modes;
- (void)performSelector:(SEL)aSelector withObject:(nullable id)anArgument afterDelay:(NSTimeInterval)delay;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(nullable id)anArgument;
+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
@end
查看文档, 使用cancelPreviousPerformRequestsWithTarget方法 .范例如下:
- (void)myButtonClicked:(id)sender
{
//取消此方法
[[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(doSth:) object:sender];
[self performSelector:@selector(doSth:) withObject:sender afterDelay:0.5f];
}
- (void)doSth:(id)sender
{
//do something ...
}
这种方法我推荐
3.此外,网上还有人用runtime处理这个问题的,这里只给出链接来,
道理其实一样, 但用runtime封装得比较好, 用get_assosiated联系了分开的部分, 类目也适合原生类的扩展, 确实比较推荐.