实现button按钮上的倒计时

创建一个button

UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];

设置位置

button.frame = CGRectMake(100, 100, 100, 100);

设置一个标签 为了后面便于获取button

button.tag = 1000;

设置背景颜色

button.backgroundColor = [UIColor cyanColor];

button按钮的核心方法target/action方法

[button addTarget: self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];

给一个时间的初值

self.number = 5;
//记录倒计时的初值
@property (nonatomic ,assign)NSInteger number;

两个关键的方法

- (void)buttonClick:(UIButton *)button
{
    //倒计时 核心  每隔一秒钟 时间递减
    //计时器(每隔多少时间调用一个方法)
    //<#(NSTimeInterval)#> 代表时间间隔
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer:) userInfo:@"button倒计时" repeats:YES];
    //计数器开始
    [timer fire];
    //关闭交互
    button.userInteractionEnabled = NO;
}

- (void)timer:(NSTimer *)timer
{
    //改button标题
    NSString *title = [NSString stringWithFormat:@"%ld",self.number--];
    UIButton *button = (UIButton *)[self.view viewWithTag:1000];
    [button setTitle:title forState:(UIControlStateNormal)];
    //判断倒计时 是否结束 标题是否为0
    if ([[button titleForState:(UIControlStateNormal)] isEqualToString:@"0"]) {
        //停止计时器
        [timer invalidate];
        //更改标题
        [button setTitle:@"重新发送验证码" forState:(UIControlStateNormal)];
        //交互打开 可以重新点击
        button.userInteractionEnabled = YES;
        //重置时间
        self.number = 5;
    }
    NSLog(@"调用了");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值