一个简单地计时器。

这是一个很简单地秒表计时器,以一秒为单位计时,实现了暂停时间和继续计时两个功能。

界面如下:



代码如下:

计时开始按钮:

- (void)start:(id)sender
{
    [_time setFireDate:[NSDate distantPast]];
//    [_time fire];
}


计时停止按钮:

- (void)stop:(id)sender
{
//    [_time invalidate];
    [_time setFireDate:[NSDate distantFuture]];
}


初始化代码:

_label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 50)];
    [_label setBackgroundColor:[UIColor whiteColor]];
    [_label setText:[NSString stringWithFormat:@"%d",currentNum]];
    [_label setTextColor:[UIColor blackColor]];
    [self.view addSubview:_label];
    
    UIButton *startBtn = [[UIButton alloc]initWithFrame:CGRectMake(50, 200, 100, 50)];
    [startBtn setTitle:@"计时开始" forState:UIControlStateNormal];
    [startBtn addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    
    
    UIButton *btnStop = [[UIButton alloc]initWithFrame:CGRectMake(200, 200, 50, 50)];
    [btnStop setTitle:@"停止" forState:UIControlStateNormal];
    [btnStop addTarget:self action:@selector(stop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnStop];
    
    
    _time = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updataUI:) userInfo:nil repeats:YES];
    [_time setFireDate:[NSDate distantFuture]];


更新UI代码:

- (void)updataUI:(id)sender
{
    currentNum++;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [_label setText:[NSString stringWithFormat:@"%d",currentNum]];
    });
    
}

好了 ,就是这么简单地一个计时器。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值