大家在做驗(yàn)證碼的時(shí)候一般都會(huì)用到倒計(jì)時(shí),基本上大家實(shí)現(xiàn)的方式都差不多,先貼出一些代碼來..
-(void)startTime{
? ? __block int timeout= 59; //倒計(jì)時(shí)時(shí)間
? ? 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){ //倒計(jì)時(shí)結(jié)束慷暂,關(guān)閉
? ? ? ? ? ? dispatch_source_cancel(_timer);
? ? ? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ? ? ? ? //設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
? ? ? ? ? ? ? ? [self.getIdentifyBtn setTitle:@"獲取驗(yàn)證碼" 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(), ^{
? ? ? ? ? ? ? ? //設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
? ? ? ? ? ? ? ? [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是我自己的,看客們根據(jù)自己項(xiàng)目來修改,那么還有一個(gè)問題,有時(shí)候用xib創(chuàng)建了按鈕,做了倒計(jì)時(shí),你會(huì)發(fā)現(xiàn)按鈕倒計(jì)時(shí)的時(shí)候會(huì)發(fā)生閃爍的問題,那么解決方法是:
修改你的button的屬性,如果是xib很簡單,直接到button的屬性中把按鈕由默認(rèn)的system改成custom即可,如果是代碼創(chuàng)建,在創(chuàng)建的時(shí)候用
self.smsButton?=?[UIButton?createButtonWithStyle:UIButtonTypeRoundedRect ?
withFrame:CGRectMake(80,0,100,30) ?
withTitle:NSLocalizedString(@"重發(fā)驗(yàn)證碼",?nil) ?
? withTitleColor:color ?
withBackgroudColor:nil ?
withNormalImage:nil ?
withHighlightedImage:nil ?
withNormalBackgroudImage:nil ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}]; ?
不可直接設(shè)置buttontype因?yàn)閎uttontype屬性是readonly的!!!
來自 https://www.cnblogs.com/changjianioser/p/5076826.html