写在前面
刚开始学习iOS开发,在此过程中学习到很多知识点,写这些的目的,首先是为了给像我一样的小白提供一些参考资料,其次是对自己所学知识的一个总结与记录。
废话不多说,下面开始。
有时候我们的app可能需要一定定时器,就是类似秒表一样的东西,点开始后,秒表开始计时,点暂停,时间停下,再点开始继续计时。另一个按钮是reset,清空数据重新开始。
准备工作
IOS有个一个NSTIME类,封装的比较好了,不需要导入其他东西
正式开始
storyboard中,在原view中拖:
一个label,用于显示时间
。outlet
一个button,用于开始,暂停功能。action
一个button,用于reset。action
私有:
isStart用于表示按钮的状态,是该显示”开始“还是”暂停“。
countTime用于计时。
<pre name="code" class="objc">@interface TrainingModeViewController (){
/*开始button的标识量。
isStarted == kIsStarting说明此时button显示-->开始
否则,button显示-->暂停
*/
BOOL isStarted ;
float countTime;
NSTimer *timer;
}
开始、暂停按钮
主要还是用了NSTimer 的scheduledTimerWithTimeInterval::::(太长不打了)这个方法,意思就是每隔多久,调用哪里的哪个方法。
这里设定是每隔0.1秒,调用self中的updateTime这个方法。
具体代码:
<pre name="code" class="objc">- (IBAction)startOrEnd:(UIButton *)sender {
//改变button状态
if (isStarted) { //button正显示开始,将改为暂停。说明将start程序
isStarted = NO;
[_startOrEndButton setTitle:@"暂停" forState:UIControlStateNormal];
//开始计时
/*
*@param Interval: 时间间隔,调用 selector
*
*/
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
} else { //button正显示暂停,将改为开始。说明将pause程序
isStarted = YES;
[_startOrEndButton setTitle:@"开始" forState:UIControlStateNormal];
//暂停计时
[timer invalidate];
}
}
#pragma mark 时间更新UI,定时回调
- (void)updateTime {
countTime +=0.1;
NSString *timeForString = [NSString stringWithFormat:@"%02d:%02d:%04.1f", (int)(countTime / 3600),(int)(countTime / 60) ,countTime - ( 60 * (int)( countTime / 60 ) )];
_timeLabel.text = timeForString;
}
重新开始按钮的action:
#pragma mark 重新开始
- (IBAction)reset:(UIButton *)sender {
//清空计时数据为0.0
countTime = 0.0f;
_timeLabel.text = @"00:00:00.0";
//其他功能处理
}
在拖label的时候最好在storyboard中设置label的text为: 00:00:00.0,一进去看到的就是这个格式。