@interface ViewController () @property (nonatomic ,strong)UIButton *btn; @property (nonatomic ,assign)NSInteger secondsCountDown;//总时间 @property (nonatomic ,strong)NSTimer *countDownTimer;//定时器 @end 创建button
-(void)createBtn{ self.btn = [UIButton buttonWithType:UIButtonTypeCustom];//UIButtonTypeSystem时会闪 self.btn.frame = CGRectMake(100, 100, 140, 100); self.btn.backgroundColor = [UIColor orangeColor]; [self.btn setTitle:@"获取验证码" forState:UIControlStateNormal]; [self.btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // [self.btn addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];//方法1:NSTimer [self.btn addTarget:self action:@selector(startTimeGCD) forControlEvents:UIControlEventTouchUpInside];//方法1:GCD [self.view addSubview:self.btn]; }方法1:NSTimer
- (void)startTime{ self.secondsCountDown = 5; self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startTimeNSTimer) userInfo:nil repeats:YES]; [self.btn setTitle:[NSString stringWithFormat:@"%ld秒后重新发送",(long)self.secondsCountDown] forState:UIControlStateNormal]; self.btn.userInteractionEnabled = NO; } - (void)startTimeNSTimer{ self.secondsCountDown -- ; [self.btn setTitle:[NSString stringWithFormat:@"%ld秒后重新发送",(long)self.secondsCountDown] forState:UIControlStateNormal]; if (self.secondsCountDown == 0) { [self.countDownTimer invalidate]; self.btn.userInteractionEnabled = YES; [self.btn setTitle:@"重新发送验证码" forState:UIControlStateNormal]; } }方法2:GCD
- (void)startTimeGCD { __block int timeout=10; //创建队列(全局并发队列) 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); //回到主线程更新UI dispatch_async(dispatch_get_main_queue(), ^{ [self.btn setTitle:@"发送验证码" forState:UIControlStateNormal]; self.btn.userInteractionEnabled = YES; }); }else{ int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds]; dispatch_async(dispatch_get_main_queue(), ^{ [self.btn setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal]; self.btn.userInteractionEnabled = NO; }); timeout--; } }); dispatch_resume(_timer); }