IOS實現(xiàn)驗證碼倒計時功能(二)
更新時間:2016年04月13日 15:26:41 作者:學(xué)偉愛OS
這篇文章主要介紹了IOS實現(xiàn)驗證碼倒計時功能,點(diǎn)擊獲取驗證碼,進(jìn)入時間倒計時,感興趣的小伙伴們可以參考一下
驗證碼倒計時按鈕的應(yīng)用是非常普遍的,該Blog就和你一起來實現(xiàn)驗證碼倒計時的效果,定義一個發(fā)送驗證碼的按鈕,添加點(diǎn)擊事件,具體內(nèi)容如下
具體代碼:
定義一個發(fā)送驗證碼的按鈕,添加點(diǎn)擊事件
//發(fā)送驗證碼按鈕 _sentCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 27 - 4 - 94, CGRectGetMinY(_registerCodeFD.frame) + 4, 94, 40)]; [_sentCodeBtn setBackgroundColor:colorWithRGBA(0, 191, 191, 0.9)]; [_sentCodeBtn setTitle:@"發(fā)送驗證碼" forState:UIControlStateNormal]; [_sentCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]]; //設(shè)置圓角 [_sentCodeBtn.layer setCornerRadius:3.0f]; [_sentCodeBtn.layer setShouldRasterize:YES]; [_sentCodeBtn.layer setRasterizationScale:[UIScreen mainScreen].scale]; //發(fā)送事件 [_sentCodeBtn addTarget:self action:@selector(sentCodeMethod) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_sentCodeBtn];
監(jiān)聽事件:
//發(fā)送驗證碼 -(void)sentCodeMethod{ NSLog(@"發(fā)送驗證碼。。"); //計時器發(fā)送驗證碼 [self sentPhoneCodeTimeMethod]; //調(diào)用發(fā)送驗證碼接口-》 } //計時器發(fā)送驗證碼 -(void)sentPhoneCodeTimeMethod{ //倒計時時間 - 60秒 __block NSInteger timeOut = 59; //執(zhí)行隊列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //計時器 -》dispatch_source_set_timer自動生成 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); dispatch_source_set_event_handler(timer, ^{ if (timeOut <= 0) { dispatch_source_cancel(timer); //主線程設(shè)置按鈕樣式-》 dispatch_async(dispatch_get_main_queue(), ^{ [_sentCodeBtn setTitle:@"發(fā)送驗證碼" forState:UIControlStateNormal]; [_sentCodeBtn setUserInteractionEnabled:YES]; }); }else{ //開始計時 //剩余秒數(shù) seconds NSInteger seconds = timeOut % 60; NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds]; //主線程設(shè)置按鈕樣式 dispatch_async(dispatch_get_main_queue(), ^{ [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; [_sentCodeBtn setTitle:[NSString stringWithFormat:@"%@S后重新發(fā)送",strTime] forState:UIControlStateNormal]; [UIView commitAnimations]; //計時器件不允許點(diǎn)擊 [_sentCodeBtn setUserInteractionEnabled:NO]; }); timeOut--; } }); dispatch_resume(timer); }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
基于iOS Realm數(shù)據(jù)庫的使用實例詳解
下面小編就為大家分享一篇基于iOS Realm數(shù)據(jù)庫的使用實例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01Objective-C const常量的優(yōu)雅使用方法
這篇文章主要為大家介紹了Objective-C const常量的優(yōu)雅使用方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08