计时3秒效果图
代码
//获取验证码
- (IBAction)getVerifiedCode:(UIButton *)sender
{
//验证码倒数计时
__block int leftTime = 60;
sender.backgroundColor = UIColorFromHex(0xBDBDBD);
[sender setTitle:[NSString stringWithFormat:@"%i秒", leftTime] forState:UIControlStateDisabled];
sender.enabled = NO;
[NSTimer bk_scheduledTimerWithTimeInterval:1 block:^(NSTimer *timer) {
if (leftTime == 0) {
sender.backgroundColor = UIColorFromHex(0xF48D2F);
sender.enabled = YES;
[sender setTitle:@"获取验证码" forState:UIControlStateNormal];
//计时完成,销毁定时器
[timer invalidate];
}
leftTime--;
[sender setTitle:[NSString stringWithFormat:@"%i秒", leftTime] forState:UIControlStateDisabled];
} repeats:YES];
}
使用了第三方库 BlocksKit,直接把控件需要调用或触发的方法写在block中。
代码中这句 [NSTimer bk_scheduledTimerWithTimeInterval: block:] 是BlocksKit对NSTimer的分类中的方法,不仅如此,BlocksKit还有对UIButton、NSArray、NSDictionary...的block方法,十分强大。用__block修饰leftTime,因为一般情况下,在block中是不能改变外部变量的值,但是在变量前用 __block 声明后就可以。
计时完成别忘了销毁定时器。