2015-04-12 56 views
0

有我要顯示爲這樣的計時器:00:00:00定時器不表示左0

然而,有時我的定時器顯示此:00:1:9。

有關如何阻止此問題的任何建議?

下面是代碼:

-(void)updateCounter:(NSTimer *)theTimer;{ 

NSTimeInterval timeInterval = [start timeIntervalSinceNow]; 

    NSInteger secondsLeft = timeInterval; 

     hours = secondsLeft/3600; 
     minutes = (secondsLeft % 3600)/60; 
     seconds = (secondsLeft %3600) % 60; 


    _myCounterLabel.text =[[NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds] stringByReplacingOccurrencesOfString:@"-" withString:@""]; 
    NSLog(@"%f interval", timeInterval); 

} 

回答

0

的問題是當你有一個負的時間間隔。 %02d將打印-1作爲-1。然後你用1而不是預期的01空字符串替換-

我不確定爲什麼要替換結果字符串中的個別負號而不是正確處理secondsLeft的負值。

並且旁註:seconds不需要雙模數計算。

嘗試這樣:

-(void)updateCounter:(NSTimer *)theTimer;{ 
    NSTimeInterval timeInterval = [start timeIntervalSinceNow]; 
    // Don't allow negative intervals 
    NSInteger secondsLeft = timeInterval >= 0 ? timeInterval : 0; 

    hours = secondsLeft/3600; 
    minutes = (secondsLeft % 3600)/60; 
    seconds = secondsLeft % 60; 

    _myCounterLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds]; 
    NSLog(@"%f interval", timeInterval); 
} 
相關問題