前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >UIButton添加倒计时

UIButton添加倒计时

作者头像
周希
发布2019-10-15 11:36:32
7280
发布2019-10-15 11:36:32
举报
文章被收录于专栏:APP自动化测试APP自动化测试

最近一个项目有获取手机短信跟邮箱验证码功能, 所以要加一个UIButton倒计时功能

例子代码如下:

代码语言:javascript
复制
 1 //获取验证码按钮
 2 - (IBAction)getButtonClick:(UIButton *)sender;
 3 
 4 #pragma mark - 获取验证码
 5 - (IBAction)getButtonClick:(UIButton *)sender
 6 {
 7     //正常状态下的背景颜色
 8     UIColor *mainColor = [UIColorcolorWithRed:84/255.0green:180/255.0blue:98/255.0alpha:1.0f];
 9     //倒计时状态下的颜色
10     UIColor *countColor = [UIColorlightGrayColor];
11     [selfsetTheCountdownButton:sender startWithTime:5title:@"获取验证码"countDownTitle:@"s"mainColor:mainColor countColor:countColor];
12 }
13 
14 #pragma mark - button倒计时
15 - (void)setTheCountdownButton:(UIButton *)button startWithTime:(NSInteger)timeLine title:(NSString *)title countDownTitle:(NSString *)subTitle mainColor:(UIColor *)mColor countColor:(UIColor *)color {
16     //倒计时时间
17     __block NSInteger timeOut = timeLine;
18     dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
19     dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, queue);
20     //每秒执行一次
21     dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0), 1.0 * NSEC_PER_SEC,0);
22     dispatch_source_set_event_handler(_timer, ^{
23 
24         //倒计时结束,关闭
25         if (timeOut == 0) {
26             dispatch_source_cancel(_timer);
27             dispatch_async(dispatch_get_main_queue(), ^{
28                 button.backgroundColor = mColor;
29                [button setTitle:titleforState:UIControlStateNormal];
30                 button.userInteractionEnabled =YES;
31             });
32         } else {
33             int seconds = timeOut % 60;
34             NSString *timeStr = [NSStringstringWithFormat:@"%0.1d", seconds];
35             dispatch_async(dispatch_get_main_queue(), ^{
36                 button.backgroundColor = color;
37                 [button setTitle:[NSStringstringWithFormat:@"%@%@",timeStr,subTitle]forState:UIControlStateNormal];
38                 button.userInteractionEnabled =NO;
39             });
40             timeOut--;
41         }
42     });
43     dispatch_resume(_timer);
44 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档