基于NSTimer的倒计时

简介: 今天做手机短信验证码的功能,不用GCD,简单的NSTimer就可以完成,不知道有没有bug,测试中。。。 #pragma mark - 倒计时 - (void)startCount { /** * 添加定时器 */ self.
+关注继续查看

今天做手机短信验证码的功能,不用GCD,简单的NSTimer就可以完成,不知道有没有bug,测试中。。。


#pragma mark - 倒计时
- (void)startCount
{
    /**
     *  添加定时器
     */
    self.currentCountDown = 120;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countDown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fire];
}

- (void)countDown{
    
    if (self.currentCountDown >0) {
        //设置界面的按钮显示 根据自己需求设置
        [self.captchaBtn setTitle:[NSString stringWithFormat:@"(%ld)重新获取",(long)self.currentCountDown] forState:UIControlStateNormal];
        //self.captchaBtn.enabled = NO;
        self.currentCountDown -= 1;
    }else{
        [self removeTimer];
    }
    
}

/**
 *  移除定时器
 */
- (void)removeTimer
{
    self.currentCountDown = 0;
    [self setCaptchaEnable:YES];
    [self.timer invalidate];
    self.timer = nil;
}


//因为iOS 7下 按钮 enabled= NO, 不能设置文字
#pragma mark - 设置按钮状态
- (void)setCaptchaEnable:(BOOL)enabled{
    //可以按
    if (enabled) {
        self.captchaBtn.userInteractionEnabled = YES;
        [self.captchaBtn setBackgroundImage:[UIImage imageNamed:@"back_red"] forState:UIControlStateNormal];
        [self.captchaBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        
    }else{
        self.captchaBtn.userInteractionEnabled = NO;
        [self.captchaBtn setBackgroundImage:[UIImage imageNamed:@"back_gray"] forState:UIControlStateNormal];
    }
}

  • 如果有什么疑问,可以在评论区一起讨论;
  • 如果有什么不正确的地方,欢迎指导!


注:本文首发于 iHTCboy's blog,如若转载,请注明来源。

目录
相关文章
|
3月前
|
运维 JavaScript 前端开发
brython | timer 计时器
brython | timer 计时器
23 1
|
8月前
NSTimer
NSTimer
32 0
|
11月前
|
Java
【Java多线程】定时器Timer
在任务的执行时间未到之前,可能判断次数很多,比较耗费CPU,而且没有必要一值判断,只需在一定时间内进行判断执行时间到没到即可,所以在还没有到执行时间时,使用wait(时间)来让该线程进行等待,在创建任务时唤醒等待即可,因为新的任务可能需要在刚才等待执行任务之前执行,也就是新创建的任务执行时间已经到了,所以要使用notify唤醒执行任务的线程继续进行判断时间是否执行,而且这个原因也是使用wait不使用sleep的原因,如果使用sleep,在新创建任务的执行时间在sleep等待结束时间之前,等待的线程没有办法唤醒,也就不能执行时间到了的任务
【Java多线程】定时器Timer
|
Android开发 数据格式 XML
Chronometer和CountDownTimer计时器
Android小知识10则(上)Android小知识10则(下)Android用5种方式实现自定义计时器, 哪种才是你的菜?github传送门 目录 前言 Chronometer的使用 CountDownTimer的使用 最后 前言 之前在A...
1228 0
|
iOS开发
NSTimer 小记
<p style="font-size:19px; line-height:normal; margin-top:0px; font-family:'Lucida Grande'"> 创建一个 Timer</p> <ul style="margin-left:30px; padding-left:0px; font-family:Verdana,Geneva,Arial,Helveti
1300 0
相关产品
云迁移中心
推荐文章
更多