您的位置:首页 > 移动开发 > IOS开发

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

2017-10-11 10:32 323 查看
倒计时按钮在项目中经常用到,为了使用方便我做了简单的封装。

下面直接上代码。

#import <UIKit/UIKit.h>

typedef void(^setBtnAction)();

@interface countdownButton : UIButton

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

@end


#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 中初始化,记得引入头文件。

#import "countdownButton.h"


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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios