2009-10-06 60 views
10

我有一個視圖uilabel和uislider。我想使用滑塊的slider.range設置標籤的時間爲00:00:00至03:00:00。意味着3小時。滑塊間隔0.5分鐘。如何顯示。我希望計時器即使在應用程序關閉時也能運行。如何在iphone中顯示uilabel的倒計時?

回答

40

首先,在應用程序關閉後,無法讓定時器繼續運行。後臺應用程序根本不允許在iPhone上使用。有很多方法可以用計時器來僞造它(應用程序退出時保存時間戳,並在開始備份時檢查它),但它不會處理在應用程序啓動之前計時器耗盡的情況向上。

至於用倒計時更新UILabel,NSTimer可能會工作。事情是這樣的,假設你有一個的NSTimer計時器,一個int secondsLeft,和一個UILabel countdownLabel在你的類:

創建定時器:

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

的updateCountdown方法:

-(void) updateCountdown { 
    int hours, minutes, seconds; 

    secondsLeft--; 
    hours = secondsLeft/3600; 
    minutes = (secondsLeft % 3600)/60; 
    seconds = (secondsLeft %3600) % 60; 
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds]; 
} 

我在我的一個應用程序中做類似的事情,但現在沒有代碼。

+0

是什麼secondsLeft的價值。 – 2009-10-06 15:30:27

+0

這就是你想要定時器運行的秒數,最有可能的設置是基於UISlider的值。 – 2009-10-06 17:41:07

+0

正如Shawn所說,在應用程序關閉後無法讓計時器繼續運行,因此請確保在應用程序發送UIApplicationWillTerminateNotification(我認爲就是這樣,我已生鏽)時記錄開始時間。當應用程序未運行時,計時器運行的唯一解決方法是使用推送通知。但這可能會很昂貴。 – pxl 2009-10-06 20:39:41

2

此錯誤代碼是錯誤的。

timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES]; 

它應該是。

timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES]; 
0

你可以保持您的計時器的運作時,您的應用程序確實進入後臺,

爲@shawn craver告訴ü你不能做到這一點,但是當應用程序進入後臺,你可以做到這一點(「未終止」)這是一個不同的事件applicationDidEnterBackground 並且你需要一些多線程GCD(Grand Central Disatch)。

plase參考此鏈接

set a timer in ios