我有一个倒数计时器,用户可以在时钟应用程序中使用倒数计时器输入他们想要开始的时间。问题是,我无法弄清楚如何使计时器实际倒计时。我已经制作了用户界面并拥有大部分代码,但我不知道我的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
方法中的内容,以便让计时器减少。
提前致谢。
答案 0 :(得分:2)
您将跟踪变量剩余的总时间。每秒都会调用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