最近一个项目有获取手机短信跟邮箱验证码功能, 所以要加一个UIButton倒计时功能
例子代码如下:
1 //获取验证码按钮 2 - (IBAction)getButtonClick:(UIButton *)sender; 3 4 #pragma mark - 获取验证码 5 - (IBAction)getButtonClick:(UIButton *)sender 6 { 7 //正常状态下的背景颜色 8 UIColor *mainColor = [UIColorcolorWithRed:84/255.0green:180/255.0blue:98/255.0alpha:1.0f]; 9 //倒计时状态下的颜色 10 UIColor *countColor = [UIColorlightGrayColor]; 11 [selfsetTheCountdownButton:sender startWithTime:5title:@"获取验证码"countDownTitle:@"s"mainColor:mainColor countColor:countColor]; 12 } 13 14 #pragma mark - button倒计时 15 - (void)setTheCountdownButton:(UIButton *)button startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(UIColor *)mColor countColor:(UIColor *)color { 16 //倒计时时间 17 __block NSInteger timeOut = timeLine; 18 dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); 19 dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue); 20 //每秒执行一次 21 dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0), 1.0 * NSEC_PER_SEC,0); 22 dispatch_source_set_event_handler(_timer, ^{ 23
24 //倒计时结束,关闭 25 if (timeOut == 0) { 26 dispatch_source_cancel(_timer); 27 dispatch_async(dispatch_get_main_queue(), ^{ 28 button.backgroundColor = mColor; 29 [button setTitle:titleforState:UIControlStateNormal]; 30 button.userInteractionEnabled =YES; 31 }); 32 } else { 33 int seconds = timeOut % 60; 34 NSString *timeStr = [NSStringstringWithFormat:@"%0.1d", seconds]; 35 dispatch_async(dispatch_get_main_queue(), ^{ 36 button.backgroundColor = color; 37 [button setTitle:[NSStringstringWithFormat:@"%@%@",timeStr,subTitle]forState:UIControlStateNormal]; 38 button.userInteractionEnabled =NO; 39 }); 40 timeOut--; 41 } 42 }); 43 dispatch_resume(_timer); 44 }