封裝按鈕倒計(jì)時(shí),一行代碼實(shí)現(xiàn)后臺也能倒計(jì)時(shí)
一般登錄注冊都會有發(fā)送驗(yàn)證碼的功能,首先實(shí)現(xiàn)該功能,我們需要做什么?
1.點(diǎn)擊按鈕,發(fā)送驗(yàn)證碼,開始倒計(jì)時(shí),按鈕不可點(diǎn)擊,以防暴力點(diǎn)擊;
2.倒計(jì)時(shí)結(jié)束,按鈕恢復(fù)點(diǎn)擊事件;
Tip:這里我們做的需求里又需要app進(jìn)入后臺,倒計(jì)時(shí)可以繼續(xù)~~~
3.app進(jìn)入后臺,倒計(jì)時(shí)可以繼續(xù)。
這里實(shí)現(xiàn)思路是:創(chuàng)建button的分類,新增一個(gè)方法,一行代碼實(shí)現(xiàn)以上所有的功能;使用GCD信號量來做按鈕倒計(jì)時(shí),實(shí)現(xiàn)app進(jìn)入后臺也可以繼續(xù)倒計(jì)時(shí),而且倒計(jì)時(shí)不會出現(xiàn)亂序的情況。好了,不多說了,直接上代碼?。?!




~~~~~~~~~~~~~~~~~~~~~~~~~~這是條分割線~~~~~~~~~~~~~~~~~~~~~~~~~~
是不是以為結(jié)束了?當(dāng)然會提供一份手敲代碼啦,哈哈哈~~~
- (void)startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle {
//倒計(jì)時(shí)時(shí)間
__block NSInteger timeout = timeLine;
? ? 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);
? ? //每秒執(zhí)行一次
? ? dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
? ? //設(shè)置這個(gè),進(jìn)入后臺也可以倒計(jì)時(shí)
? ? NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:timeout];
? ? dispatch_source_set_event_handler(_timer, ^{
? ? ? ? ?int interval = [endTime timeIntervalSinceNow];
? ? ? ? //倒計(jì)時(shí)結(jié)束,關(guān)閉
? ? ? ? if(interval <= 0) {
? ? ? ? ? ? dispatch_source_cancel(_timer);
? ? ? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ? ? ? ? self.enabled = YES;
? ? ? ? ? ? ? ? [self setTitle:title forState:UIControlStateNormal];
? ? ? ? ? ? });
? ? ? ? }else {
? ? ? ? ? ? int allTime = (int)timeLine + 1;
? ? ? ? ? ? int seconds = interval % allTime;
? ? ? ? ? ? NSString *timeStr = [NSString stringWithFormat:@"重新發(fā)送(%0.2d)",seconds];
? ? ? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{
? ? ? ? ? ? ? ? [self setTitle:[NSString stringWithFormat:@"%@%@",timeStr,subTitle] forState:UIControlStateNormal];
? ? ? ? ? ? ? ? self.enabled = NO;
? ? ? ? ? ? });
? ? ? ? ? ? timeout --;
? ? ? ? } ? ?});
? ? dispatch_resume(_timer);
}
結(jié)語:有什么不對的地方請指正,謝謝!覺得有用的同學(xué)可以點(diǎn)個(gè)贊哦,一起學(xué)習(xí),一起成長!