【问题标题】:how to finish my countdown timer in objective c?如何在目标 c 中完成我的倒数计时器?
【发布时间】:2012-12-29 10:43:47
【问题描述】:

我有一个倒数计时器,用户可以使用倒数计时器输入他们想要开始的时间,就像在时钟应用程序中一样。问题是,我不知道如何让计时器真正倒计时。我已经制作了 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 方法中发生了什么来让计时器减少。

提前致谢。

【问题讨论】:

  • 你有什么变量来跟踪时间?我没有看到它的变量,或者这就是您要的?

标签: objective-c timer nstimer uidatepicker


【解决方案1】:

您将使用变量跟踪剩余的总时间。 updateTimer 方法将每秒被调用一次,每次调用 updateTimer 方法时,您将剩余时间变量减少 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    相关资源
    最近更新 更多