<pre name="code" class="objc">NSString *const KTitleStr = @"获取验证码";
NSInteger const KTimeNum = 20;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setTitle:KTitleStr forState:UIControlStateNormal];
[self setBackgroundColor:[UIColor blueColor]];
self.titleLabel.font=[UIFont systemFontOfSize:12];
[self setTitle:@"" forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.userInteractionEnabled = YES;
_timeNumber = KTimeNum;
[self addTarget:self action:@selector(btnTitleChange:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
- (void)btnTitleChange:(UIButton *)btn
{
// 创建倒计时
_timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self selector:@selector(timeChanges) userInfo:NULL repeats:YES];
[_timer fire];
}
- (void)timeChanges
{
if (_timeNumber == 0) {
[self setTitle:KTitleStr forState:UIControlStateNormal];
[self setBackgroundColor:[UIColor blueColor]];
self.titleLabel.font=[UIFont systemFontOfSize:12];
[self setTitle:@"" forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
self.userInteractionEnabled = YES;
_timeNumber = KTimeNum;
[_timer invalidate];//停止timer
} else {
[self setBackgroundColor:[UIColor colorWithPatternImage:_downBgImg]];
[self setTitle:[NSString stringWithFormat:@"%d",_timeNumber] forState:UIControlStateNormal];
[self setTitle:[NSString stringWithFormat:@"%d",_timeNumber] forState:UIControlStateHighlighted];
self.userInteractionEnabled = NO;
_timeNumber -= 1;
}
}
简单封装一个短信验证码按钮
1. 创建按钮,添加点击事件
2. 创建NSTimer 倒计时,定义NSTimerInterVal触发间隔
设置属性外边调用
@interface AuthButton : UIButton
{
@private
NSTimer *_timer;
}
/**
* 触发间隔
*/
@property (nonatomic, assign) NSTimeInterval timeInterval;
/**
* 时钟
*/
@property (nonatomic, strong, readonly) NSTimer *timer;
/**
* 倒计时按钮背景
*/
@property (nonatomic, strong) UIImage *downBgImg;
@end