倒计时功能的实现
2016-10-01 10:15
204 查看
在ios中我们在做验证码的时候 就少不了要用到倒计时 所以 这里就介绍两种实现倒计时的方法
第一种是使用NSTimer方式实现:
第二种方式 使用GCD的方式实现:
第一种是使用NSTimer方式实现:
@implementation SYViewController { int totalSeconds; NSTimer *downTimer; UILabel *labelText; } - (void)viewDidLoad { [super viewDidLoad]; totalSeconds = 60; labelText = [[UILabel alloc] init]; labelText.frame = CGRectMake(100, 100, 300, 30); [self.view addSubview:labelText]; downTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerChange) userInfo:nil repeats:YES]; labelText.text = [NSString stringWithFormat:@"%d",totalSeconds]; } - (void)timerChange { totalSeconds--; labelText.text = [NSString stringWithFormat:@"%d",totalSeconds]; if (totalSeconds==0) { [downTimer invalidate]; downTimer = nil; } } }
第二种方式 使用GCD的方式实现:
__block int timeout=60; //倒计时时间 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_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据自己需求设置 labelText.text = @"倒计时结束"; }); }else{ int minutes = timeout / 60; int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新获取验证码",minutes, seconds]; dispatch_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据自己需求设置 labelText.text = [NSString stringWithFormat:@"%@",strTime]; }); timeout--; } }); dispatch_resume(_timer);
相关文章推荐
- 用C#实现倒计时功能
- ASP.NET实现无刷新倒计时功能
- android倒计时功能的实现(CountDownTimer)
- android倒计时功能的实现(CountDownTimer)
- android倒计时功能的实现(CountDownTimer)
- 使用JS实现倒计时功能(http://www.cnblogs.com/doll-net)
- 十二、初学.NET—利用AJAX在页面头部显示服务器当前时间,并实现倒计时功能
- 简单几行javascript代码,实现动态倒计时功能
- ASP.NET实现无刷新倒计时功能,团购倒计时
- Android菜鸟笔记-利用CountDownTimer实现倒计时功能
- ASP.NET实现无刷新倒计时功能
- android倒计时功能的实现(CountDownTimer)
- 实现注册页面中的倒计时功能代码
- 实现注册页面中的倒计时功能代码
- 贴一段基于jquery实现的倒计时功能的函数
- Android利用CountDownTimer类实现倒计时功能
- [笔记] PPT幻灯片也RIA——PPT实现倒计时功能
- PPT实现倒计时功能(VBA实现)
- 用JS实现倒计时功能
- android倒计时功能的实现(CountDownTimer)