iOS 验证码 小技术之 UIButton NSTimer 计时器
2015-10-24 18:01
281 查看
#import "ViewController.h" @interface ViewController () //自定义按钮属性 button 方便下文更改名称title @property (nonatomic, retain) UIButton * button; // 自定义属性 time 作为控制验证码间隔时间 @property (nonatomic, assign) NSInteger time; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 自定义一个UIButton 作为 发送验证码按钮 self.button = [UIButton buttonWithType:(UIButtonTypeSystem)]; // 设置button 位置 self.button.frame = CGRectMake(100, 100, 100, 30); // 设置 按钮背景颜色 self.button.backgroundColor = [UIColor greenColor]; // 设置 按钮名称 [self.button setTitle:@"发送验证码" forState:(UIControlStateNormal)]; // 给按钮添加点击事件 [self.button addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)]; // 将按钮添加到主界面 [self.view addSubview:self.button]; // 设置验证码间隔时间 (可根据实际使用需要设置) 单位为秒 self.time = 5; } // 实现按钮点击方法 - (void)actionButton:(UIButton *)button { // 创建定时器 可以进行循环 // userInfo 可以看做一个参数或者标示符 NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTimer:) userInfo:@"123" repeats:YES]; // 计时器启动 [timer fire]; // 在进行时间倒计时的时候 关闭button交互 self.button.userInteractionEnabled = NO; } // 实现 timer 的时间变化方法 - (void)myTimer:(NSTimer *)timer { // 在按钮上面显示剩余时间 [self.button setTitle:[NSString stringWithFormat:@"%ld", self.time--] forState:(UIControlStateNormal)]; // 当时间减到0的时候 将计时器 归零 if (self.time < 0) { // 当时间为0 时改变按钮名称 [self.button setTitle:@"重新发送" forState:(UIControlStateNormal)]; // 开启button 点击事件 self.button.userInteractionEnabled = YES; // 计时器失效 [timer invalidate]; // 将时间重置为5 self.time = 5; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
运行成果截图展示:
相关文章推荐
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- java自动生成验证码插件-kaptcha
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- 如何识别高级的验证码的技术总结第1/4页
- PHP 验证码不显示只有一个小红叉的解决方法
- asp汉字中文图片验证码
- PHP实现简单汉字验证码
- php生成动态验证码gif图片
- php生成验证码函数
- php 验证码制作(网树注释思想)
- C#验证码识别基础方法实例分析
- javascript点击才出现验证码
- node.js WEB开发中图片验证码的实现方法
- 验证码的三个常见漏洞和修复方法
- 声音验证码制作方法