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

2025-05-29 0 40

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

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

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

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

?

1

2

3

4

5

6
- (void)buttonClicked:(id)sender

{

//这里是关键,点击按钮后先取消之前的操作,再进行需要进行的操作

[[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonClicked:) object:sender];

[self performSelector:@selector(buttonClicked: )withObject:sender afterDelay:0.2f];

}

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

?

1

2

3

4

5

6

7

8
-(void)buttonClicked:(id)sender{

self.button.enabled = NO;

[self performSelector:@selector(changeButtonStatus) withObject:nil afterDelay:1.0f];//防止用户重复点击

}

-(void)changeButtonStatus{

self.button.enabled = YES;

}

或者使用:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18
- (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.

如果大家有更好的解决办法,欢迎大家留言说明。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS 防止按钮多次点击造成多次响应的方法 https://www.kuaiidc.com/92226.html

相关文章

发表评论
暂无评论