2012-12-29 271 views
1

我有一個倒數計時器,用戶可以輸入他們想要使用倒數計時器的時間,如在時鐘應用程序中。問題是,我無法弄清楚如何讓計時器倒計時。我已經制作了UI並擁有大部分代碼,但我不知道updateTimer方法中會出現什麼結果。這裏是我的代碼:如何在目標c中完成我的倒數計時器?

- (void)updateTimer 
{ 
    //I don't know what goes here to make the timer decrease... 
} 

- (IBAction)btnStartPressed:(id)sender { 
    pkrTime.hidden = YES; //this is the timer picker 
    btnStart.hidden = YES; 
    btnStop.hidden = NO; 
    // Create the timer that fires every 60 sec  
    stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                 target:self 
                selector:@selector(updateTimer) 
                userInfo:nil 
                repeats:YES]; 
} 

- (IBAction)btnStopPressed:(id)sender { 
    pkrTime.hidden = NO; 
    btnStart.hidden = NO; 
    btnStop.hidden = YES; 
} 

請讓我知道在updateTimer方法讓計時器減少發生的事情。

在此先感謝。

+0

什麼變化你有跟蹤時間?我沒有看到它的變量,或者是你要求的嗎? –

回答

1

你會跟蹤一個變量的剩餘時間。 updateTimer方法將每秒調用一次,並且每次調用updateTimer方法時,都會將剩餘時間減少1(1秒)。我在下面給出了一個例子,但我已將updateTimer重命名爲reduceTimeLeft。

SomeClass.h

#import <UIKit/UIKit.h> 

@interface SomeClass : NSObject { 
    int timeLeft; 
} 

@property (nonatomic, strong) NSTimer *timer; 

@end 

SomeClass.m

#import "SomeClass.h" 

@implementation SomeClass 

- (IBAction)btnStartPressed:(id)sender { 
    //Start countdown with 2 minutes on the clock. 
    timeLeft = 120; 

    pkrTime.hidden = YES; 
    btnStart.hidden = YES; 
    btnStop.hidden = NO; 

    //Fire this timer every second. 
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                 target:self 
               selector:@selector(reduceTimeLeft:) 
                userInfo:nil 
                repeats:YES]; 
} 

- (void)reduceTimeLeft:(NSTimer *)timer { 
    //Countown timeleft by a second each time this function is called 
    timeLeft--; 
    //When timer ends stop timer, and hide stop buttons 
    if (timeLeft == 0) { 
     pkrTime.hidden = NO; 
     btnStart.hidden = NO; 
     btnStop.hidden = YES; 

     [self.timer invalidate]; 
    } 
    NSLog(@"Time Left In Seconds: %i",timeLeft); 
} 

- (IBAction)btnStopPressed:(id)sender { 
    //Manually stop timer 
    pkrTime.hidden = NO; 
    btnStart.hidden = NO; 
    btnStop.hidden = YES; 

    [self.timer invalidate]; 
} 

@end