iOS 防止按钮多次点击造成多次响应的方法

    xiaoxiao2021-03-25  119

    在日常开发中经常会碰到一种bug就是因为用户快速点击某个按钮,导致页面重复push或者重复发送网络请求。这样的问题既对用户体验有影响,而且还会一定程度上增加服务器的压力。

    目前,我为了防止按钮快速点击主要使用以下两种办法

    1.在每次点击时先取消之前的操作(网上看到的方法)

    - (void)buttonClicked:(id)sender { //这里是关键,点击按钮后先取消之前的操作,再进行需要进行的操作 [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClicked:) object:sender]; [self performSelector:@selector(buttonClicked: )withObject:sender afterDelay:0.2f]; }

    2.点击后将按钮置为不可点击状态,几秒后恢复

    -(void)buttonClicked:(id)sender{ self.button.enabled = NO; [self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:1.0f];//防止用户重复点击 } -(void)changeButtonStatus{ self.button.enabled = YES; }

    或者使用:

    - (void) timeEnough { UIButton *btn=(UIButton*)[self.view viewWithTag:33]; btn.selected=NO; [timer invalidate]; timer=nil; } - (void) btnDone:(UIButton*)btn { if(btn.selected) return; btn.selected=YES; [self performSelector:@selector(timeEnough) withObject:nil afterDelay:3.0]; //使用延时进行限制。 //to do something. }
    转载请注明原文地址: https://ju.6miu.com/read-20001.html

    最新回复(0)