2012-03-23 60 views
0

我正在爲iPhone構建一個簡單的健身/訓練應用程序。用戶可以從表格中選擇一種類型的訓練課程,將其帶到包含秒錶的視圖控制器。該視圖的標籤由可變數組填充。以不同的時間間隔更改uilabel文本

我可以讓秒錶工作,並從數組中填充初始標籤,但無法弄清楚如何讓標籤在設定的時間間隔內發生變化。這些時間間隔將不會是正常的,所以可能會在10分鐘,然後是25,然後是45等。我一直試圖通過If語句來執行此操作,例如定時器== 25。我確信這是一個基本的解決方案,但我是編程新手,無法解決問題。

定時器的代碼如下:

- (void)updateTimer 
{ 
    NSDate *currentDate = [NSDate date]; 
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"HH:mm:ss.S"]; 
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
    NSString *timeString=[dateFormatter stringFromDate:timerDate]; 
    timerLabel.text = timeString; 
} 

啓動計時器:

- (IBAction)startTimerButton:(id)sender { 

    if (timer == nil) { 
     startDate = [NSDate date]; 

     // Create the stop watch timer that fires every 0.1s 

     timer = [NSTimer scheduledTimerWithTimeInterval:1.0/10 
               target:self 
               selector:@selector(updateTimer) 
               userInfo:nil 
               repeats:YES]; 

    } 

    else { 
     return; 
    } 
} 
+0

到目前爲止運行此代碼的結果是什麼? – 2012-03-23 15:15:24

+0

沒有生成錯誤和秒錶正常工作。我無法弄清楚如何做If語句。我嘗試了「if(timer == 5)[nextLable; setText ...]」,但是我得到一個錯誤'INT隱式轉換爲'NSTimer'不允許ARC' – pig70 2012-03-23 15:27:21

+0

Try(timer.timeInterval == 5)。 閱讀NSTimer的類參考https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html – 2012-03-23 15:33:40

回答

0

我不太清楚你以後。如果您將時間間隔設置爲10分鐘/ 25分鐘等而不是1.0/10,那麼在您的時間觸發代碼中,您將知道計時器的時間間隔。

您可以始終使用timeInterval實例方法查詢時間間隔。也許如下。

- (void)updateTimer:(NSTimer*)timer 
{ 
    if ([timer timeInterval] == 10 * 60) // 10 minutes have elapsed 
    { 
     // Do something for this timer. 
    } 
    else if ([timer timeInterval] == 20 * 60) // 20 minutes have elapsed 
    { 
    } 
} 

請注意,我已經添加了計時器作爲參數傳遞給您的updateTimer功能。然後,您必須在scheduledTimerWithTimeInterval方法中使用@selector(update:)(在末尾帶有冒號!)選擇器。當您的回調選擇器被調用時,它將傳遞給它的計時器。

或者,如果你有一個指針,你在你的「startTimerButton」你可以使用創建的計時器如下:

- (void)updateTimer:(NSTimer*)timer 
{ 
    if (timer == myTenMinuteTimer) // 10 minutes have elapsed 
    { 
     // Do something for this timer. 
    } 
    else if (timer == myTwentyMinuteTimer) // 20 minutes have elapsed 
    { 
    } 
} 

注意的是,在第二個原因你的指針比較兩個對象和使用它,就像在第一次比較兩個對象的方法的值一樣,所以對象不一定是指向同一對象的指針,以便被評估爲真。

希望這會有所幫助!

+0

謝謝你們。將與此一起去。 – pig70 2012-03-24 09:26:06