我正在尝试创建一个倒计时计时器,一个连接到文本字段的 IBOutlet,从 60 秒减少到 0。我不确定
一个。如何将重复次数限制在 60 次和
B.如何在 advanceTimer 中递减倒计时:
- (IBAction)startCountdown:(id)sender
{
NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advanceTimer:) userInfo:nil repeats:YES];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:countdownTimer forMode:NSDefaultRunLoopMode];
}
- (void)advanceTimer:(NSTimer *)timer
{
[countdown setIntegerValue:59];
}
最佳答案
到目前为止,您的方向是正确的。
坚持使用您已有的代码,这里是 advanceTimer
方法应该如何使其工作:
- (void)advanceTimer:(NSTimer *)timer
{
[countdown setIntegerValue:([countdown integerValue] - 1)];
if ([countdown integerValue] == 0)
{
// code to stop the timer
}
}
编辑: 为了使整个事情更加面向对象,并避免每次都从字符串转换为数字并返回,我会做这样的事情:
// Controller.h:
@interface Controller
{
int counter;
IBOutlet NSTextField * countdownField;
}
@property (assign) int counter;
- (IBAction)startCountdown:(id)sender;
@end
// Controller.m:
@implementation Controller
- (IBAction)startCountdown:(id)sender
{
counter = 60;
NSTimer *countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(advanceTimer:)
userInfo:nil
repeats:YES];
}
- (void)advanceTimer:(NSTimer *)timer
{
[self setCounter:(counter -1)];
[countdownField setIntegerValue:counter];
if (counter <= 0) { [timer invalidate]; }
}
@end
而且,如果您可以使用绑定(bind),您可以简单地将文本字段的 intValue
绑定(bind)到 Controller
的 counter
属性。这将允许您删除类接口(interface)中的 IBOutlet
和 advanceTimer
中的 setIntegerValue:
行。
更新:删除了两次将计时器添加到运行循环的代码。感谢 Nikolai Ruhe 和 nschmidt 注意到该错误。
更新:根据 nschmidt,使用 setIntegerValue
方法简化代码。
编辑: (void)advanceTimer:(NSTimer *)timer 定义中的拼写错误......导致恼人的“无法识别的选择器发送到实例”异常
关于objective-c - 倒计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1032776/