这是将别人写的倒计时的代码从两个类整合到一个类里面 可能我弄到一个类里面看着代码会比较多
这是一个两个按钮的倒计时 可以将下面的停止按钮根据需要酌情添加 代码如下:
.m文件
#import "ViewController.h"
#define FirstTitle @"获取验证码"
#define SecondTitle @"重新获取验证码"
@interface ViewController ()
@property (nonatomic,strong) UIButton *button;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,assign)NSInteger totalSecond;
@property (nonatomic,strong, nullable)UIButton *buttonStop;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.viewaddSubview:self.button];
[self.viewaddSubview:self.buttonStop];
}
- (UIButton *)button
{
if (_button ==nil) {
_button = [[UIButtonalloc]initWithFrame:CGRectMake(80,200, 150, 44)];
_button.backgroundColor = [UIColorblueColor];
[_buttonsetTitle:FirstTitleforState:UIControlStateNormal];
[_buttonaddTarget:selfaction:@selector(btnClick:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:_button];
}
return_button;
}
- (void)btnClick:(UIButton *)btn
{
[selfstart];
}
- (NSTimer *)timer
{
if (!_timer) {
_timer = [NSTimerscheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(timerCountDown:)
userInfo:nil
repeats:YES];
}
return_timer;
}
- (void)start
{
_totalSecond =59;
[self.buttonsetEnabled:NO];
[[NSRunLoopcurrentRunLoop]addTimer:self.timerforMode:NSRunLoopCommonModes];
}
-(void)timerCountDown:(NSTimer *)theTimer {
self.totalSecond--;
if (self.totalSecond <0) {
[selfstop];
} else {
NSString *title = [NSStringstringWithFormat:@"剩余%ld秒",(long)self.totalSecond+1];
[self.buttonsetTitle:title forState:UIControlStateNormal];
[self.buttonsetTitle:title forState:UIControlStateDisabled];
}
}
- (UIButton *)buttonStop
{
if (!_buttonStop) {
_buttonStop = [[UIButtonalloc]initWithFrame:CGRectMake(80,300, 150, 44)];
_buttonStop.backgroundColor = [UIColorblueColor];
[_buttonStopsetTitle:@"Stop"forState:UIControlStateNormal];
[_buttonStopaddTarget:selfaction:@selector(stopCountDown)forControlEvents:UIControlEventTouchUpInside];
}
return_buttonStop;
}
- (void)stopCountDown
{
[selfstop];
}
- (void)stop{
[self.buttonsetEnabled:YES];
if (self.timer) {
if ([self.timerrespondsToSelector:@selector(isValid)]) {
if ([self.timerisValid]) {
[self.timerinvalidate];
self.timer =nil;
}
}
}
[self.buttonsetTitle:SecondTitleforState:UIControlStateNormal];
[self.buttonsetTitle:SecondTitleforState:UIControlStateDisabled];
}