2013-02-26 120 views
0

在我的應用程序中,我讓用戶使用UIDatePicker'sCountDownTimer設置了倒計時計時器。使用UIDatePicker在iOS中進行計時器倒計時

我有一個UILabel顯示計數時間當用戶從CountDownTimer中選擇時間時,我想顯示在CoutDownTimer中選擇的用戶下來的coumt,如下圖所示。

enter image description here

所以我檢索用戶從CountDownTimer選擇了與下面的代碼

self.dateFormatter = [[NSDateFormatter alloc] init]; 
[self.dateFormatter setDateFormat:@"HH:mm:ss"]; 

self.sleepTimer = [NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO]; 

當到達00:00,我想觸發一個事件計數的時間。

我不知道如何減少每秒鐘的計數。

謝謝你的幫助。

+0

您需要'NSTimer'。 http://stackoverflow.com/questions/1449035/how-do-i-use-nstimer – graver 2013-02-26 13:28:36

+0

是的,我知道,但我不知道如何減少1每秒 – 2013-02-26 13:29:20

+0

你需要一個變量來減少每次計時器火災直到它達到0. – graver 2013-02-26 13:30:07

回答

2

保存您UIDatePicker(該值以秒爲單位)中的一個實例變量稱爲有點像countDownDuration財產secondsLeft

self.sleepTimer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES]; 

這會每秒鐘調用您的方法timerFired:。用012減去secondsLeft 1.用剩餘時間更新你的UILabel(在格式化時將你的秒數格式化爲hh:mm:ss - See this question)。驗證倒計時是否有剩餘時間,並在倒計時完成時採取適當的措施(secondsLeft <= 0)。

一旦倒計時完成,請記得清理;

[self.sleepTimer invalidate]; 
self.sleepTimer = nil; 
+0

非常感謝兄弟。我知道了。 :) – 2013-02-26 14:11:06

2

你可以做到這一點:

[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(decrementByOne:) userInfo:nil repeats:YES]; 
+0

我不知道如何減少NSDateFormatter.plz的幫助1。 – 2013-02-26 13:37:17

+0

我沒有說dateFormatter。我說過要製作一個計數器,從每秒開始計數。然後上面的選擇器會每秒調用它,並且你的計數器將被遞減並且顯示它。 – 2013-02-26 13:42:58

0

把你的日期,保存到一個屬性,看看NSDates

– dateByAddingTimeInterval: 

所以,如果你

[self.date dateByAddingTimeInterval:-1]; 

你會減少1秒的日期。之後,使用新的計算日期更新UI。

而且你可以打包所有的代碼在一個函數調用執行此功能:

performSelector:withObject:afterDelay: