所以我正在尝试设置一个基本计时器,但失败得很惨。基本上我想要的只是在用户单击按钮时启动 60 秒计时器,并用剩余时间更新标签(如倒计时)。我创建了我的标签和按钮,并在 IB 中连接了它们。接下来,我为按钮创建了一个 IBAction。现在,当我尝试根据计时器更新标签时,我的应用程序搞砸了。这是我的代码:
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 1
target: self
selector:@selector(updateLabelDisplay)
userInfo: nil repeats:YES];
我还有一个 updateLabelDisplay 函数,它确定计时器运行了多少次,然后从 60 中减去该数字并将该数字显示在倒计时标签中。谁能告诉我我做错了什么?
最佳答案
好的,对于初学者来说,如果您还没有检查一下:Official Apple Docs about Using Timers
根据您的描述,您可能需要如下所示的代码。我已经对行为做出了一些假设,但您可以根据口味进行调整。
此示例假设您想要保留对计时器的引用,以便您可以暂停它或进行其他操作。如果不是这种情况,您可以修改 handleTimerTick 方法,使其将 NSTimer* 作为参数,并在计时器过期后使用它使计时器失效。
@interface MyController : UIViewController
{
UILabel * theLabel;
@private
NSTimer * countdownTimer;
NSUInteger remainingTicks;
}
@property (nonatomic, retain) IBOutlet UILabel * theLabel;
-(IBAction)doCountdown: (id)sender;
-(void)handleTimerTick;
-(void)updateLabel;
@end
@implementation MyController
@synthesize theLabel;
// { your own lifecycle code here.... }
-(IBAction)doCountdown: (id)sender
{
if (countdownTimer)
return;
remainingTicks = 60;
[self updateLabel];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(handleTimerTick) userInfo: nil repeats: YES];
}
-(void)handleTimerTick
{
remainingTicks--;
[self updateLabel];
if (remainingTicks <= 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
}
-(void)updateLabel
{
theLabel.text = [[NSNumber numberWithUnsignedInt: remainingTicks] stringValue];
}
@end
关于objective-c - NSTimer问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3220695/