您的位置:首页 > 产品设计 > UI/UE

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


运行成果截图展示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 验证码 NSTimer