0
有兴趣为用户创建计时器。创建支持小时,分钟秒,秒分秒数的计时器定时器iPhone sdk
我想知道是否必须分别跟踪所有整数变量或者如果我可以使用日期格式化程序。
我正在使用-scheduledTimerfoo以秒为单位调用-updateLabel方法,但它在100秒后看起来有点可怕。我有点像“小时:分钟:秒:分秒”来显示。
干杯
山姆
有兴趣为用户创建计时器。创建支持小时,分钟秒,秒分秒数的计时器定时器iPhone sdk
我想知道是否必须分别跟踪所有整数变量或者如果我可以使用日期格式化程序。
我正在使用-scheduledTimerfoo以秒为单位调用-updateLabel方法,但它在100秒后看起来有点可怕。我有点像“小时:分钟:秒:分秒”来显示。
干杯
山姆
NSDateFormatter仅用于格式化日期,而不是时间间隔。一个更好的方法是记录你启动计时器的时间,并且每秒更新一次标签,从启动计时器开始已经过去了多少时间。
- (void)startTimer {
// Initialize timer, with the start date as the userInfo
repeatTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLabel) userInfo:[NSDate date] repeats:YES];
}
- (void)updateLabel:(NSTimer *)timer {
// Get the start date, and the time that has passed since
NSDate *startDate = (NSDate *)[timer userInfo];
NSTimeInterval timePassed = [[NSDate date] timeIntervalSinceDate:startDate];
// Convert interval in seconds to hours, minutes and seconds
int hours = timePassed/(60 * 60);
int minutes = (timePassed % (60 * 60))/60;
int seconds = ((timePassed % (60 * 60)) % 60);
NSString *time = [NSString stringWithFormat:@"%i:%i:%i", hours, minutes, seconds];
// Update the label with time string
}