2010-04-13 131 views
9

我有我的計時器代碼設置,它都是猶太教,但我希望我的標籤顯示「分鐘:秒」,而不是僅僅幾秒鐘。iPhone:NSTimer倒計時(顯示分鐘:秒)

-(void)countDown{ 

    time -= 1; 

    theTimer.text = [NSString stringWithFormat:@"%i", time]; 

    if(time == 0) 
    { 
    [countDownTimer invalidate]; 
    } 
} 

我已經將「時間」設置爲600或10分鐘。但是,我希望顯示屏顯示10:59,10:58等,直到達到零。

我該怎麼做?

謝謝!

回答

19
int seconds = time % 60; 
int minutes = (time - seconds)/60; 
theTimer.text = [NSString stringWithFormat:@"%d:%.2d", minutes, seconds]; 
+0

這是偉大的!但是,一旦秒數低於10,它會顯示「9:9」,「9:8」等。 有沒有辦法使「9:09」,「9:08」? – user298261 2010-04-13 06:25:07

+5

當然。 'NSString * padZero = @「」; if(seconds <10)padZero = @「0」; theTimer.text = [NSString stringWithFormat:@「%i:%@%i」,minutes,padZero,seconds];' – 2010-04-13 14:31:00

+11

我寧願使用printf格式來填充這樣的數字:'[NSString stringWithFormat:@「%d :%。2d「,分鐘,秒]' – 2010-04-13 15:42:54

0

的時候,我寫了第一個答案的小升級,它刪除從NSIntegerint相關的衝突:

NSInteger secondsLeft = 987; 
int second = (int)secondsLeft % 60; 
int minutes = ((int)secondsLeft - second)/60; 
theTimer.text = [NSString stringWithFormat:@"%02d:%02d", minutes, second]];