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

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

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值