iOS-计时器发送验证码
2016-04-13 14:26
513 查看
效果图如下:
定义一个发送验证码的按钮,添加点击事件
监听事件:
定义一个发送验证码的按钮,添加点击事件
//发送验证码按钮 _sentCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 27 - 4 - 94, CGRectGetMinY(_registerCodeFD.frame) + 4, 94, 40)]; [_sentCodeBtn setBackgroundColor:colorWithRGBA(0, 191, 191, 0.9)]; [_sentCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal]; [_sentCodeBtn.titleLabel setFont:[UIFont systemFontOfSize:13.0f]]; //设置圆角 [_sentCodeBtn.layer setCornerRadius:3.0f]; [_sentCodeBtn.layer setShouldRasterize:YES]; [_sentCodeBtn.layer setRasterizationScale:[UIScreen mainScreen].scale]; //发送事件 [_sentCodeBtn addTarget:self action:@selector(sentCodeMethod) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_sentCodeBtn];
监听事件:
//发送验证码 -(void)sentCodeMethod{ NSLog(@"发送验证码。。"); //计时器发送验证码 [self sentPhoneCodeTimeMethod]; //调用发送验证码接口-》 } //计时器发送验证码 -(void)sentPhoneCodeTimeMethod{ //倒计时时间 - 60秒 __block NSInteger timeOut = 59; //执行队列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //计时器 -》dispatch_source_set_timer自动生成 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); dispatch_source_set_event_handler(timer, ^{ if (timeOut <= 0) { dispatch_source_cancel(timer); //主线程设置按钮样式-》 dispatch_async(dispatch_get_main_queue(), ^{ [_sentCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal]; [_sentCodeBtn setUserInteractionEnabled:YES]; }); }else{ //开始计时 //剩余秒数 seconds NSInteger seconds = timeOut % 60; NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds]; //主线程设置按钮样式 dispatch_async(dispatch_get_main_queue(), ^{ [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:1.0]; [_sentCodeBtn setTitle:[NSString stringWithFormat:@"%@S后重新发送",strTime] forState:UIControlStateNormal]; [UIView commitAnimations]; //计时器件不允许点击 [_sentCodeBtn setUserInteractionEnabled:NO]; }); timeOut--; } }); dispatch_resume(timer); }
相关文章推荐
- IOS 拍照,系统相册 拿照片地理位置,还有修改时间最新时间
- iOS开发-GCD 常见用法二(一次性代码)
- iOS开发-GCD 常见用法一(延迟执行)
- 用Storyboard布局页面
- Nagios web页面,提示找不到/nagios页面
- ionic ios archive error Cordova/CDVViewController.h
- iOS属性文字NSAttributedString
- MBProgressHUD解析
- iOS 开发— JSONS字符串转字典
- iOS 8 Auto Layout界面自动布局系列5-自身内容尺寸约束、修改约束、布局
- iOS隐藏一个View(定时器)
- iPhone4/4s运行iOS7慢怎么办
- iOS开发之Xcode pch头文件简单使用方法 让写代码更简单!
- IOS 计步器
- iOS FMDB同时修改多个参数的值
- 清理缓存iOS
- 最简单详细快捷集成支付宝支付
- iOS 明明导入了图片,可Xcode却说找不到图片
- iOS开发问题集锦
- iOS GCD最大并发控制