最近公司做手机注册功能. 需要用到倒计时的button,然后自己简单封装了一个, 内部使用NSTimer计时器,主要属性有
demo地址:https://github.com/lwy121810/WYCountdownButtonDemo
/**button的标题**/
@property (nonatomic , copy) NSString *title_normal;
/**计时结束后显示的文字的 默认跟title_normal一样*/
@property (nonatomic , copy) NSString *title_end;
/**button的字体颜色 默认lightGrayColor*/
@property (nonatomic , strong) UIColor *titleColor_normal;
/**倒计时的总时间 默认10s**/
@property (nonatomic , assign) NSInteger totalSeconds;
效果:
实现:
其实原理很简单 就不多说了, 主要代码有:
#pragma mark - private
//开始计时
- (void)startCountdown
{
if ([_timer isValid]) {//timer还有效的话直接返回
return;
}
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(startCountdown:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)startCountdown:(NSTimer *)timer
{
_second--;
if (_second < 0) {
[self stopCountDown];
return;
}
_isCountdowning = YES;
self.enabled = NO;
NSString *title = [NSString stringWithFormat:@"%zd秒",_second];
[self setTitle:title forState:UIControlStateNormal];
[self setTitle:title forState:UIControlStateDisabled];
}
//结束计时
- (void)stopCountDown
{
if (_timer) {
if ([_timer isValid]) {
[_timer invalidate];
_second =_totalSeconds;
_isCountdowning = NO;
self.enabled = YES;
_timer = nil;
[self setTitle:self.title_end forState:UIControlStateNormal];
}
}
}
请大神们多多指正!