月圆之夜,紫禁之巅,一剑西来,天外飞仙。

0%

iOS学习笔记--封装倒计时按钮

倒计时按钮在项目中经常用到,为了使用方便我做了简单的封装。
下面直接上代码。

1
2
3
4
5
6
7
8
9
10
#import <UIKit/UIKit.h>

typedef void(^setBtnAction)();

@interface countdownButton : UIButton

//倒计时开始回调
@property(nonatomic,strong)setBtnAction setBtnAction;

@end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#import "countdownButton.h"

@interface countdownButton()

@property(nonatomic,strong)UIButton * btn;

@end

@implementation countdownButton
{

NSInteger secondsCountDown;
NSTimer * countDownTimer;

}
-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];

if (self)
{
secondsCountDown = 60;

[self setBtnUI];
}

return self;
}

-(void)setBtnUI
{

[self setBackgroundColor:[UIColor orangeColor]];

[self setTitle:@"获取验证码" forState:UIControlStateNormal];

[self.titleLabel setFont:[UIFont systemFontOfSize:14.0]];

[self addTarget:self action:@selector(countDownAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)countDownAction:(UIButton *)sender
{

[self setTitle:[NSString stringWithFormat:@"%zd s",secondsCountDown] forState:UIControlStateNormal];

countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];

[self setEnabled:NO];

if(self.setBtnAction)
{
self.setBtnAction();
}

}

-(void)timeFireMethod
{
secondsCountDown--;

[self setTitle:[NSString stringWithFormat:@"%zd s",secondsCountDown] forState:UIControlStateNormal];

if (secondsCountDown<0)
{
[countDownTimer invalidate];

[self setEnabled:YES];

[self setTitle:@"获取验证码" forState:UIControlStateNormal];

secondsCountDown = 60;
}

}
@end

在需要使用倒计时按钮的地方初始化。
这里我在ViewController 中初始化,记得引入头文件。

1
#import "countdownButton.h"
1
2
3
4
5
6
7
8
9
10
11
12
countdownButton * btn = [[countdownButton alloc]initWithFrame:CGRectMake(100, 100, 90, 40)];

[btn setBackgroundColor:[UIColor purpleColor]];

[btn setSetBtnAction:^(){

//这里写入倒计时开始时需要执行的事件。
NSLog(@"倒计时开始");

}];

[self.view addSubview:btn];

demo 地址:https://github.com/xiaobai0134/XBCountDownButton