验证码倒计时
2016-08-24 本文已影响20人
凡尘一笑
我们经常会在注册,或者更换密码时候需要获取验证码
先给大家看一下效果
just.gif直接给代码,这个比较容易,注意我这里倒计时是0.2秒,所以比较快。基本都看得懂
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UIButton * timeButton;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, strong)UIButton * btn;
@end
@implementation ViewController
{
NSInteger _time;
}
- (void)viewDidLoad {
[super viewDidLoad];
_time = 60;
self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
_btn.backgroundColor = [UIColor orangeColor];
[_btn setTitle:@"获取验证码" forState:UIControlStateNormal];
_btn.titleLabel.font = [UIFont systemFontOfSize:15];
[_timeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self refreshButtonWidth];
[self.view addSubview:self.btn];
}
- (void)refreshButtonWidth{
CGFloat width = 0;
if (_btn.enabled){
width = 100;
} else {
width = 100;
}
_btn.center = CGPointMake(self.view.frame.size.width/2, 200);
_btn.bounds = CGRectMake(0, 0, width, 40);
//每次刷新,保证区域正确
[_btn setBackgroundImage:[self imageWithColor:[UIColor orangeColor] andSize:_btn.frame.size] forState:UIControlStateNormal];
[_btn setBackgroundImage:[self imageWithColor:[UIColor lightGrayColor] andSize:_btn.frame.size] forState:UIControlStateDisabled];
}
- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)aSize{
CGRect rect = CGRectMake(0.0f, 0.0f, aSize.width, aSize.height); UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
return image;
}
- (void)btnAction:(UIButton *)sender{
sender.enabled = NO;
[self refreshButtonWidth];
[sender setTitle:[NSString stringWithFormat:@"%zi", _time] forState:UIControlStateNormal];
_timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeDown) userInfo:nil repeats:YES];
}
- (void)timeDown{
_time --;
if (_time == 0) {
[_btn setTitle:@"重新获取" forState:UIControlStateNormal];
_btn.enabled = YES;
[self refreshButtonWidth];
[_timer invalidate];
_timer = nil;
_time = 60 ;
return;
}
[_btn setTitle:[NSString stringWithFormat:@"%zi", _time] forState:UIControlStateNormal];
}