倒计时

实现倒计时功能

//
//  CountDownViewController.m
//  倒计时again

/*
  写一个自己的VC,命名为CountDownViewController
 */

#import "CountDownViewController.h"

@interface CountDownViewController() {
    NSInteger _seconds;//秒数
    UIButton *_button;//按钮
    NSTimer *_timer;//计时器
}

@end

@implementation CountDownViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        self.view.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}

#pragma mark -- 设置视图
- (void)setUpView {
    //创建button
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((self.view.frame.size.width-100)/2, (self.view.frame.size.height-80)/2, 100, 80)];
    
    button.backgroundColor = [UIColor grayColor];
    [button setTitle:@"倒计时" forState:UIControlStateNormal];
    button.showsTouchWhenHighlighted = YES;
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 4;
    
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    _button = button;
    [self.view addSubview:button];
}

#pragma mark -- 按钮响应事件
- (void)buttonClicked:(UIButton *)button {
    [_button setEnabled:NO];//倒计时期间使按钮不可用
    
    _seconds = 10;//倒计时10秒
    
    [_button setTitle:@"10" forState:UIControlStateNormal];//初始10秒
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTheTime:) userInfo:nil repeats:YES];
    
}

#pragma mark -- 计时器响应事件
- (void)changeTheTime:(NSTimer *)timer {
    if (_seconds>1) {
        --_seconds;
        [_button setTitle:[NSString stringWithFormat:@"%ld",_seconds] forState:UIControlStateNormal];
    }
    else {
        _seconds = 10;
        [_button setTitle:@"重新倒计时" forState:UIControlStateNormal];
        [_timer invalidate];//关闭并销毁计时器
        [_button setEnabled:YES];//打开按钮
    }
}


@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值