这是一个很简单地秒表计时器,以一秒为单位计时,实现了暂停时间和继续计时两个功能。
界面如下:
代码如下:
计时开始按钮:
- (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]];
});
}
好了 ,就是这么简单地一个计时器。