使用GCD实现发送短信验证码效果
2016-05-16 13:50
447 查看
- (IBAction)buttonActon:(UIButton *)sender { sender.userInteractionEnabled = NO; // 等待的秒数 __block int count = 5; // 获取全局队列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 实例化计时器 _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); // 设置计时器 dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); // 设置计时器事件处理 dispatch_source_set_event_handler(_timer, ^{ if (count == 0) { // 取消计时器 dispatch_source_cancel(_timer); // 在主队列里处理 dispatch_async(dispatch_get_main_queue(), ^{ // 将按钮置为正常状态 sender.userInteractionEnabled = YES; sender.titleLabel.font = [UIFont systemFontOfSize:15]; sender.backgroundColor = [UIColor orangeColor]; [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [sender setTitle:@"发送验证码" forState:UIControlStateNormal]; }); } else { NSString *str = [NSString stringWithFormat:@"剩余(%d)s",count]; // 在主队列里处理 dispatch_async(dispatch_get_main_queue(), ^{ // 按钮显示剩余等待时间 sender.backgroundColor = [UIColor grayColor]; [sender setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal]; [sender setTitle:str forState:UIControlStateNormal]; }); count--; } }); // 开启timer dispatch_resume(_timer); } - (void)dealloc { // 取消计时器 if (_timer) dispatch_source_cancel(_timer); }
相关文章推荐
- codeforces 276D 贪心
- iOS常见警告和错误集锦
- UVa 10200 Prime Time
- jquery子元素过滤选择器
- Ubuntu安装JDK与环境变量配置
- DNS信息收集-DIG
- Google开源的FlexboxLayout
- HDU 5689 Problem E
- keepalived实现Lvs-dr集群的高可用
- Types of NoSQL databases
- 比较全面的MySQL优化参考
- 记一次,关于思杰虚拟化XEN-API服务无法启动
- 禅道的目录结构
- mysql 为某一数据库下所有表中添加相同字段
- Java出错 Error:Could not create the Java Virtual Machine Error:A fatal exception has occurred
- 布局文件-include标签使用
- 客户端如何更具需要连接不同的服务端
- Ubuntu 16.04 LTS安装好之后需要做的15件事
- java 获取打包成exe后的exe程序路径
- 如何使用ADB_WIFI