UIButton重复点击,重复触发,怎么办



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 ...
}

这种方法我推荐

posted @ 2016-03-28 02:23  YH_Coding  阅读(636)  评论(0编辑  收藏  举报