dispatch倒计时的实现

主要用于项目中获取验证码环节,参考了之前搜索的网络资料,权作记录.
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];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,235评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,664评论 4 61
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,092评论 19 139
  • 我们常常发现,销售人员已经整理好了客户资料,目标客户也选择与确定下来,但是,在准备拜访客户前,却遭到了客户的直接拒...
    奋斗的番茄阅读 4,453评论 0 0
  • ps这是一篇没头没脑的文章 单纯自己明志 苦笑脸。 时间是一个不折不扣的小偷。 我还清楚记得你说,巴啦啦考试还有半...
    陶瓷姑娘阅读 3,382评论 0 0

友情链接更多精彩内容