iOS 按钮倒计时

2019-10-15  本文已影响0人  sj1910

使用倒计时获取验证码是app中最长遇到的,常用的方法有三种

屏幕快照 2019-10-15 上午10.40.26.png 屏幕快照 2019-10-15 上午10.40.35.png
NSTimer
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(handleTimer) userInfo:nil repeats:YES];
Thread
- (void)firstBtnAction:(UIButton  *)sender {
    //创建一个后台线程执行计时操作
    [self performSelectorInBackground:@selector(timerThread) withObject:nil];
}

- (void)timerThread {
    for (int i = TIMECOUNT; i >= 0 ; i--) {
        self.count--;
        //切换到主线程中更新UI
        [self performSelectorOnMainThread:@selector(updateFirstBtn) withObject:nil waitUntilDone:YES];
        sleep(1);
    }
}
GCD(我使用的)

创建一个UIButton的分类

@interface UIButton (countDown)

/**
 *  倒计时按钮
 *
 *  @param timeLine 倒计时总时间
 *  @param title    还没倒计时的title
 *  @param subTitle 倒计时中的子名字,如时、分
 */
- (void)startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(unsigned int)mainHex countColor:(unsigned int)countHex;

@end
#import "UIButton+countDown.h"

@implementation UIButton (countDown)

- (void)startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(unsigned int)mainHex countColor:(unsigned int)countHex{
    
    __weak typeof(self) weakSelf = self;
    //倒计时时间
    __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);
    //每秒执行一次
    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);
            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf setBackgroundColor:RGBOF(mainHex)];
                [weakSelf setTitle:title forState:UIControlStateNormal];
                [weakSelf setTitleColor:kBaseBlueColor forState:(UIControlStateNormal)];
                weakSelf.userInteractionEnabled = YES;
            });
        } else {
            int allTime = (int)timeLine + 1;
            int seconds = timeOut % allTime;
            NSString *timeStr = [NSString stringWithFormat:@"%d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf setBackgroundColor:RGBOF(countHex)];
                [weakSelf setTitle:[NSString stringWithFormat:@"%@%@",timeStr,subTitle] forState:UIControlStateNormal];
                [weakSelf setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
                weakSelf.userInteractionEnabled = NO;
            });
            timeOut--;
        }
    });
    dispatch_resume(_timer);
}

@end

上一篇 下一篇

猜你喜欢

热点阅读