1

我有一个倒数计时器,用户可以在其中输入他们想要从使用倒数计时器开始的时间,就像在时钟应用程序中一样。问题是,我不知道如何让计时器真正倒计时。我已经制作了 UI 并拥有大部分代码,但我不知道updateTimer我所拥有的方法会发生什么。这是我的代码:

- (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让计时器减少的方法中的内容。

提前致谢。

4

1 回答 1

2

您将使用变量跟踪剩余的总时间。updateTimer 方法将每秒被调用一次,每次调用 updateTimer 方法时,您将剩余时间变量减少 1(一秒)。我在下面给出了一个示例,但我已将 updateTimer 重命名为 reduceTimeLeft。

一些类.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
于 2012-12-29T01:47:53.643 回答