闻道丶iOS(尝鲜版)深入浅出iOS程序员

dispatch倒计时的实现

2017-03-28  本文已影响64人  henu_Larva

主要用于项目中获取验证码环节,参考了之前搜索的网络资料,权作记录.
TimerCountDown.h文件内:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface TimerCountDown : NSObject

/**
 倒计时<获取验证码>
 @param inButton 获取验证码的点击按钮
 @param duration 倒计时时长
 */
+ (void)startCountDown:(UIButton *)inButton duration:(NSInteger)duration;
@end

TimerCountDowm.m 文件内:

#import "TimerCountDown.h"

@implementation TimerCountDown

+ (void)startCountDown:(UIButton *)inButton duration:(NSInteger)duration {
    
    __block NSInteger timeout = duration;
    
    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(), ^{
                [inButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                [inButton setTitleColor:[UIColor colorWithRed:39/255.0 green:138/255.0 blue:228/255.0 alpha:1] forState:UIControlStateNormal];
                inButton.userInteractionEnabled = YES;
            });
        } else {
            //正在倒计时
            NSInteger seconds = timeout % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:1 animations:^{
                    [inButton setTitle:[NSString stringWithFormat:@"%ld秒后重发",seconds] forState:UIControlStateNormal];
                    [inButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                    inButton.userInteractionEnabled = NO;
                }];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

@end

使用方式:
1.导入头文件

#import "TimerCountDown.h"

2.在获取验证码按钮的点击事件内:

- (IBAction)test:(id)sender {
    [TimerCountDown startCountDown:sender duration:10];
}
上一篇下一篇

猜你喜欢

热点阅读