和大多数游戏一样,我以“01:05”格式看到计时器
我正在尝试实现一个计时器,并且在重置时我需要将计时器重置为“00:00”。
此计时器值应位于标签中。
如何创建递增的计时器?比如00:00 --- 00:01 --- 00:02 ..........像dat一样。
建议
问候
答案 0 :(得分:25)
我用过的一个简单的方法是:
//In Header
int timeSec = 0;
int timeMin = 0;
NSTimer *timer;
//Call This to Start timer, will tick every second
-(void) StartTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
//Event called every time the NSTimer ticks.
- (void)timerTick:(NSTimer *)timer
{
timeSec++;
if (timeSec == 60)
{
timeSec = 0;
timeMin++;
}
//Format the string 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
//[timeLabel setStringValue:timeNow];
timeLabel.text= timeNow;
}
//Call this to stop the timer event(could use as a 'Pause' or 'Reset')
- (void) StopTimer
{
[timer invalidate];
timeSec = 0;
timeMin = 0;
//Since we reset here, and timerTick won't update your label again, we need to refresh it again.
//Format the string in 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
// [timeLabel setStringValue:timeNow];
timeLabel.text= timeNow;
}
答案 1 :(得分:4)
这应该给你一个相当准确的计时器,至少是肉眼。这不会刷新视图,只会更新时间和标签:
//call this on reset. Take note that this timers cannot be used as absolutely correct timer like a watch for example. There are some variation.
-(void) StartTimer
{
self.startTime = [NSDate date] //start dateTime for your timer, ensure that date format is correct
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
-(void) timerTick
{
NSTimeInterval timeInterval = fabs([self.startTime timeIntervalSinceNow]); //get the elapsed time and convert from negative value
int duration = (int)timeInterval; // cast timeInterval to int - note: some precision might be lost
int minutes = duration / 60; //get the elapsed minutes
int seconds = duration % 60; //get the elapsed seconds
NSString *elapsedTime = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds]; //create a string of the elapsed time in xx:xx format for example 01:15 as 1 minute 15 seconds
self.yourLabel.text = elapsedTime; //set the label with the time
}
答案 2 :(得分:1)
创建一个NSDate类型的对象,例如“现在”。之后,请遵循以下代码:
self.now = [NSDate DAte];
long diff = -((long)[self.now timeIntervalSinceNow]);
timrLabel.text = [NSString stringWithFormat:@"%02d:%02d",(diff/60)%60,diff%60];
答案 3 :(得分:0)
暂停计时器(基于Hector204答案):
\__________^^^^^^^_________/ -------------------- not more than once
\_____________/ ----- other conditions