2013-07-25 68 views
3

我有一個簡單的計時器使用,是用一個按鈕被激活。它從60運行到0沒有問題,但我想要停止並按下按鈕重置定時器。我已經設法停止它,當按下按鈕使用下面的代碼,但出於某種原因不能讓它重置並在60停止。這應該很簡單,但它不工作。有什麼建議麼?停止和重置NSTimer

定時器使用簡單的動作

- (IBAction)timerStart:(id)sender { 

if(!secondCounter == 0){ 
     [countdownTimer invalidate]; 
    } 
    else { 
      [self setTimer]; 
    } 
} 

代碼使用定時器

- (void)timerRun { 
    secondCounter = secondCounter - 1; 
    int minutes = secondCounter; 

    NSString *timerOutput = [NSString stringWithFormat:@"%d", minutes ]; 
    countDownLabel.text = timerOutput; 

    if(secondCounter == 0){ 
     [countdownTimer invalidate]; 
     countdownTimer = nil; 
    } 
} 

- (void)setTimer { 
    secondCounter = 60; 
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES]; 

} 
+0

謝謝..它對我很有用 – Aayushi

回答

2

你的意思是停止定時器設置?計時器不會停止。你想不得不countDownLabel.text顯示60?當您使計時器無效時,它將停止運行,並調用timerRun方法如果要重新啓動計時器,請再次撥打setTimer函數。我想你的意思是在[countdownTimer invalidate];之後有countDownLabel.text = @"60",當你再次點擊按鈕時,計時器將重新開始,並且會改變標籤。讓我知道這是你在找什麼。

基督教說你要重置secondCounter

secondCounter = 0; 
+0

Hi @Yan。目前,它使計時器無效,並使用您建議的代碼將值返回到60.但是,當我再次按下按鈕時,它不會重新啓動計時器。相反,它是一個死鎖。有什麼想法嗎?必須在我的'if'代碼中。 – memyselfandmyiphone

+0

謝謝你,我的邏輯有瑕疵 – memyselfandmyiphone

6

您需要設置秒下降到0,否則你總是無效的計時器,但從來沒有再次啓動:

- (IBAction)timerStart:(id)sender { 
    if(!secondCounter == 0) { 
     [countdownTimer invalidate]; 
     secondCounter = 0; 
    } 
    else { 
     [self setTimer]; 
    } 
} 
+0

謝謝基督徒。我接受了Yans的回答,因爲我使用了他的答案的兩個部分,儘管你的回答很有幫助。我upvoted。 – memyselfandmyiphone