我正在開發一個QuiZ應用程序。它需要一個倒數計時器,因爲我想在75:00.00(mm:ss.SS)啓動一個計時器,並通過減少1毫秒將其減少到00:00.00(mm:ss.SS)。我想顯示一個提醒,即時間!當時間到達00:00.00(mm:ss.SS)時。NSTimer減少秒/毫秒的時間
我通過下面的鏈接
Stopwatch using NSTimer incorrectly includes paused time in display
我正在開發一個QuiZ應用程序。它需要一個倒數計時器,因爲我想在75:00.00(mm:ss.SS)啓動一個計時器,並通過減少1毫秒將其減少到00:00.00(mm:ss.SS)。我想顯示一個提醒,即時間!當時間到達00:00.00(mm:ss.SS)時。NSTimer減少秒/毫秒的時間
我通過下面的鏈接
Stopwatch using NSTimer incorrectly includes paused time in display
這是一個簡單的解決方案,您的問題。
聲明
@interface ViewController : UIViewController
{
IBOutlet UILabel * result;
NSTimer * timer;
int currentTime;
}
- (void)populateLabelwithTime:(int)milliseconds;
-(IBAction)start;
-(IBAction)pause;
@end
定義
- (void)viewDidLoad
{
[super viewDidLoad];
currentTime = 270000000; // Since 75 hours = 270000000 milli seconds
}
-(IBAction)start{
timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
}
-(IBAction)pause{
[timer invalidate];
}
- (void)updateTimer:(NSTimer *)timer {
currentTime -= 10 ;
[self populateLabelwithTime:currentTime];
}
- (void)populateLabelwithTime:(int)milliseconds {
int seconds = milliseconds/1000;
int minutes = seconds/60;
int hours = minutes/60;
seconds -= minutes * 60;
minutes -= hours * 60;
NSString * result1 = [NSString stringWithFormat:@"%@%02dh:%02dm:%02ds:%02dms", (milliseconds<[email protected]"-":@""), hours, minutes, seconds,milliseconds%1000];
result.text = result1;
}
使用縮短定時器下面的代碼顯示的時間。
double dblRemainingTime=60; //1 minute
if(dblRemainingTime >0)
{
dblRemainingTime -= 1;
int hours,minutes, seconds;
hours = dblRemainingTime/3600;
minutes = (dblRemainingTime - (hours*3600))/60;
seconds = fmod(dblRemainingTime, 60);
[lblRemainingTime setText:[NSString stringWithFormat:@"%02d:%02d",minutes, seconds]];
}
else
alert('Time up buddy');
+1了詳細的解釋。保持。 – 2012-04-21 09:14:57
海它工作正常,有一些變化...我有滾動視圖,其中我顯示的時間..如果我拖動滾動視圖時間不計算(在背景也)...我必須做的。 ..? – SriKanth 2012-04-21 12:33:01
添加此代碼以在滾動期間啓用計時器 ........................................ .......................................... - (IBAction)start { timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateTimer :) userInfo:nil repeatats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; } – 2012-04-22 06:15:54