iOS倒计时的两种实现方式

今天项目中遇到获取验证码之后有一个倒计时功能的实现,百度了一下,有两种实现方式的,再次总结一下,以便日后需要查看,也方面其他的人查看,不多说了直接贴代码吧:

第一种:NSTimer

-在倒计时开始之后,让button处于一种不可点击的状态,直至倒计时结束。

[self.vCodeBtn setEnabled:NO];

count = 60;

NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(openFire:) userInfo:nil repeats:YES];

-函数实现方法:

-(void)openFire:(NSTimer *)time

{

count--;

NSString *miao = [NSString stringWithFormat:@"%ld",(long)count];

[self.vCodeBtn setTitle:miao forState:0];

if (count == 1)

{

[self.vCodeBtn setTitle:@"Reacquire" forState:0];

[self.vCodeBtn setEnabled:YES];

[time invalidate];

}

}

第二种:使用GCD来实现:

__block int timeout=300; //倒计时时间

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行

dispatch_source_set_event_handler(_timer, ^{

if(timeout<=0){ //倒计时结束,关闭

dispatch_source_cancel(_timer);

dispatch_release(_timer);

dispatch_async(dispatch_get_main_queue(), ^{

//设置界面的按钮显示 根据自己需求设置

。。。。。。。。

});

}else{

int minutes = timeout / 60;

int seconds = timeout % 60;

NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新获取验证码",minutes, seconds];

dispatch_async(dispatch_get_main_queue(), ^{

//设置界面的按钮显示 根据自己需求设置

。。。。。。。。

});

timeout--;

}

});

dispatch_resume(_timer);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1.{ NSTimer *timer; }- (void)viewDidLoad { timer = [NSTim...
    叶飞楼阅读 759评论 0 0
  • NSTimer方式 @interface TimerButton ()@property (nonatomic, ...
    Jessica124阅读 458评论 0 0
  • 目录(GCD): 关键词 混淆点 场景应用 总结 1. 关键词 线程概念: 独立执行的代码段,一个线程同时间只能执...
    Ryan___阅读 1,364评论 0 3
  • iOS中计时器常用的有两种方式 使用NSTimer类(Swift 中更名为 Timer) NSTimer 常用的初...
    superDg阅读 1,939评论 0 1
  • 终于,我可以提笔记录那些年 你熟悉却已陌生的脸 分手时我们没有愉快地说再见 这是我留有的遗憾 你手机里她灿烂的笑脸...
    朗秋阅读 335评论 0 3

友情链接更多精彩内容