2012-06-25 309 views
-3

我創建了一個從10到0的倒數計時器。我創建了一個顯示秒數的計數器。現在我想讓標籤顯示櫃檯分鐘和秒鐘,就像那樣:00:00。 我該怎麼做? 這裏是我的倒數代碼:分秒倒數計時器

-(void)countdown 
{ 
    countdownCounter -= 1; 
    countdown.text = [NSString stringWithFormat:@"%i", countdownCounter]; 

} 

-(IBAction)strat:(id)sender 
{ 
    countdownCounter = 10; 
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self  selector:@selector(countdown) userInfo:nil repeats:YES]; 
    } 

} 

謝謝!

回答

2

完全一樣的方法,只需添加另一個計時器。

countdownTimer2 = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(countdown2) userInfo:nil repeats:YES]; 

-(void)countdown2 
{ 
    countdownCounterMinutes -= 1; 
} 

and change countdown to 

-(void)countdown 
{ 
    countdownCounter -= 1; 
    countdown.text = [NSString stringWithFormat:@"%i%i", countdownCounterMinutes, countdownCounter]; 

} 
+0

有沒有其他的方式來做一個標籤的整個計時器? – cnaaniomer

3

這可以使用一次和一個標籤完成。請嘗試使用下面的代碼:

int seconds = [countDown.text intValue] % 60; 
int minutes = ([countDown.text intValue]/60) % 60; 
countDown.text = [NSString stringWithFormat:@"%2d:%02d", minutes, seconds]; 
+0

如果我還想要十分之一秒(毫秒)? – cnaaniomer

+0

@cnaaniomer看到我編輯的答案,不是100%關於這個,但它應該像轉換整數浮點數和格式化他們顯示小數位一樣簡單。 –

+0

這是一個更好的解決方案。 – Dustin

1

的人到底答案我做它這樣誰:

-(IBAction)start 
{ 
    timer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self  selector:@selector(updateTimer:) userInfo:nil repeats:YES]; 
} 

-(void)updateTimer:(NSTimer *)timer { 
    currentTime -= 10 ; 
    [self populateLabelwithTime:currentTime]; 
    if(currentTime <=0) 
     [timer invalidate]; 
} 


- (void)populateLabelwithTime:(int)milliseconds { 
    seconds = milliseconds/1000; 
    minutes = seconds/60; 
    hours = minutes/60; 

    seconds -= minutes * 60; 
    minutes -= hours * 60; 

    NSString * result1 = [NSString stringWithFormat:@"%@%02d:%02d:%02d:%02d", (milliseconds<[email protected]"-":@""), hours, minutes, seconds,milliseconds%1000]; 
    result.text = result1; 

} 

在viewDidLoad中我設置currentTime的以毫秒爲單位的倒計時時間。 希望你明白...

0

我用這種方式格式化數字(從浮點數)與分鐘和秒 謝謝你的答案幫助。 (希望這有助於另一個)

- (void)ticTimer 
{ 
    self.current -= self.updateSpeed; 
    CGFloat progress = self.current/self.max; 
    [self populateLabelwithTimeFormatted:self.current]; 
    /// TimeLabelNode.text = [NSString stringWithFormat:@"%f", progress]; 

    // * Time is over 
    if (self.current <= self.min) { 
     [self stop]; 
     _TimeLabelNode.text= @"time up!"; 
    } 
} 

- (void)populateLabelwithTimeFormatted:(float)time { 
    //convert float into mins and seconds format 
    int mytime = (int) _current; 
    int seconds = mytime%60; 
    int minutes = mytime/60 % 60; 

    NSString * result1 = [NSString stringWithFormat:@"%2d:%02d", minutes, seconds]; 
    _TimeLabelNode.text = result1; 
}