【问题标题】:Timer label isn't counting down计时器标签没有倒计时
【发布时间】:2013-07-20 16:46:22
【问题描述】:

这不是所有的代码。我已经确保我已经正确声明了所有内容,但是标签没有随着“秒”的减少而改变。

我不知道为什么在 'subtractTime' 中我已经使 timerLabel.text 等于字符串,格式使用秒数“应该”并且在我使用警报重置游戏时倒计时,所以即使标签没有改变,我知道它正在倒计时,否则不会从等于 0 的“秒”触发警报。

- (void)setupGame;
{
    seconds = 30;
    count = 0;

    timerLabel.text = [NSString stringWithFormat: @"Time: %i", seconds];
    scoreLabel.text = [NSString stringWithFormat: @"Score: %i", count];

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0
         target:self
         selector:@selector(subtractTime)
         userInfo:nil
         repeats:YES];

}
- (void)subtractTime;
{
    seconds--;
    timerLabel.text = [NSString stringWithFormat:@"Time: %i", seconds];

    if (seconds == 0)
    {
        [timer invalidate];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Time is up !" 
                          message: [NSString stringWithFormat: @"You Scored %i points", count]
                          delegate:self
                          cancelButtonTitle: @"Play Again"
                          otherButtonTitles:nil];

        [alert show];
    }

}
@end

【问题讨论】:

  • 如果您在 IB 中创建了timerLabel,它是否连接正确?
  • IBOutlet UILabel *scoreLabel; IBOutlet UILabel *timerLabel; NSInteger 计数; NSInteger 秒; NSTimer *timer;
  • 您是否在 Interface Builder 中建立了连接?
  • 在subtractTime方法之后你多了一个;
  • 我不确定,因为我是一个非常新手的 obj-c 程序员。什么是界面生成器?

标签: objective-c


【解决方案1】:

确保在 Storyboard/Interface builder 中,您的标签已正确连接到 viewXontroller 的 .h 文件。测试这一点的一个好方法是在 XIB 上用“时间:”以外的东西“启动”你的标签,而是用像“foo”这样无意义的东西。这样一来,您就可以准确判断标签是否发生了变化,而不是排除您的 Int 值是否显示不正确。

【讨论】:

  • 添加`assert(timerLabel != nil, @"timerlabel nil!");
  • Rob 有什么用?
  • 在你的项目中切换助手视图(它看起来像 XCode 窗口右上角的一个小燕尾服图标)。在左窗格中打开您的 XIB/Storyboard,在右窗格中打开您的 viewController 的 .h 文件。右键单击并从 XIB 中的标签拖动到 .h 文件中标签的声明。
  • 感谢 D80 它解决了我的问题,因为我没有正确链接 =] Nooby 错误。
  • @user2602189:使用断言来验证变量的状态。如果断言失败,您的程序将停止。断言有助于调试。更好的是,使用 NSAssert。 stackoverflow.com/a/2003432/2462469
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多