IOS - NSTimer实现倒数(获取手机验证码)
2016-08-03 本文已影响63人
lxf_2013
//倒数60秒
#define oneMinute 60
static int _countDown = oneMinute;
//创建timmer
@property (nonatomic, weak) NSTimer *timer;
- (NSTimer *)timer{
if (!_timer) {
//每秒更新一次button的值
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateButton) userInfo:nil repeats:YES];
}
return _timer;
}
- (void)updateButton{
//每秒都会减一,模以60剩下的就是实际的值
_countDown = (_countDown - 1 + oneMinute) % oneMinute;
if (_countDown == 0) {//到了0秒的时候
//setFireDate: //重新设置定时器开始运行的时间
self.timer.fireDate = [NSDate distantFuture];
//到了0获取验证码按钮可以重新点击
self.buttonGetIDCode.enabled = YES;
}
NSString *title = [NSString stringWithFormat:@"获取成功%d", _countDown];
self.buttonGetIDCode.titleLabel.text = title;
[self.buttonGetIDCode setTitle:title forState:UIControlStateDisabled];
}