博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UIButton添加倒计时
阅读量:7217 次
发布时间:2019-06-29

本文共 2073 字,大约阅读时间需要 6 分钟。

 

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

例子代码如下:

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 }

 

转载于:https://www.cnblogs.com/zhouxihi/p/5990273.html

你可能感兴趣的文章
大容量分区命令parted
查看>>
从输入 URL 到页面加载完成的过程中都发生了什么事情?
查看>>
实例讲解JQuery中this和$(this)区别
查看>>
centos 7 静态ip地址模板
查看>>
影响系统性能的20个瓶颈
查看>>
shell的详细介绍和编程(上)
查看>>
软件开发性能优化经验总结
查看>>
面试题编程题05-python 有一个无序数组,如何获取第K 大的数,说下思路,实现后的时间复杂度?...
查看>>
kendo grid序号显示
查看>>
Spring 教程(二) 体系结构
查看>>
Indexes
查看>>
2.Web中使用iReport 整合----------创建html格式的
查看>>
异常备忘:java.lang.UnsupportedClassVersionError: Bad version number in .class file
查看>>
最全三大框架整合(使用映射)——applicationContext.xml里面的配置
查看>>
初步理解Java的三大特性——封装、继承和多态
查看>>
知识点积累(一)
查看>>
iphone-common-codes-ccteam源代码 CCFile.m
查看>>
python:浅析python 中__name__ = '__main__' 的作用
查看>>
修改tomcat端口后不能IP访问问题
查看>>
review board
查看>>