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
}