大家在做驗證碼的時候一般都會用到倒計時,基本上大家實現的方式都差不多,先貼出一些代碼來..
-(void)startTime{
__block int timeout= 59; //倒計時時間
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); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結束,關閉
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//設置界面的按鈕顯示 根據自己需求設置
[self.getIdentifyBtn setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
self.getIdentifyBtn.userInteractionEnabled = YES;
});
}else{
//? ? ? ? ? ? int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//設置界面的按鈕顯示 根據自己需求設置
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[self.getIdentifyBtn setTitle:[NSString stringWithFormat:@"%@秒后重發(fā)",strTime] forState:UIControlStateNormal];
[UIView commitAnimations];
self.getIdentifyBtn.userInteractionEnabled = NO;
});
timeout--;
}
});
dispatch_resume(_timer);
}
上面代碼的btn是我自己的,看客們根據自己項目來修改,那么還有一個問題,有時候用xib創(chuàng)建了按鈕,做了倒計時,你會發(fā)現按鈕倒計時的時候會發(fā)生閃爍的問題,那么解決方法是:
修改你的button的屬性,如果是xib很簡單,直接到button的屬性中把按鈕由默認的system改成custom即可,如果是代碼創(chuàng)建,在創(chuàng)建的時候用
self.view.backgroundColor = [UIColor whiteColor];
UIButton *clickButton = [UIButton buttonWithType:UIButtonTypeCustom];
clickButton.frame = CGRectMake(0, 0, 80, 40);
clickButton.center = self.view.center;
clickButton.layer.cornerRadius = 5;
clickButton.layer.masksToBounds = YES;
clickButton.backgroundColor = [UIColor orangeColor];
[clickButton setTitle:@"獲取驗證碼" forState:UIControlStateNormal];
clickButton.titleLabel.font = [UIFont systemFontOfSize:14];
[clickButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[clickButton addTarget:self action:@selector(respondsToButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:clickButton];
不可直接設置buttontype因為buttontype屬性是readonly的!!!