【问题标题】:How to add milliseconds to a stopwatch app?如何将毫秒添加到秒表应用程序?
【发布时间】:2014-09-07 15:30:22
【问题描述】:

好的,所以我将本教程中的秒表应用代码基于此处http://iphonedev.tv/blog/2013/7/7/getting-started-part-3-adding-a-stopwatch-with-nstimer-and-our-first-class 我喜欢它的设置方式,但我不知道如何添加百分之一秒,有人知道怎么做吗?

我的 ViewController.m 文件

#import "ViewController.h"
#import "Foundation/Foundation.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (NSTimer *)createTimer
{
     return [NSTimer scheduledTimerWithTimeInterval:0.01
                                        target:self
                                      selector:@selector(timerTicked:)
                                      userInfo:nil
                                       repeats:YES];
}

- (void)timerTicked:(NSTimer *)timer
{
     _currentTimeInSeconds++;

     self.timeLabel.text = [self formattedTime:_currentTimeInSeconds];
}

- (NSString *)formattedTime:(int)totalSeconds
{
    int hundredths = totalSeconds % 60;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;

    return [NSString stringWithFormat:@"%02d:%02d:%02d.%02d", hours, minutes, seconds, hundredths];
}

- (IBAction)startButtonPressed:(id)sender
{
    if (!_currentTimeInSeconds)
    {
        _currentTimeInSeconds = 0 ;
    }

    if (!_theTimer)
    {
        _theTimer = [self createTimer];
    }
}

- (IBAction)stopButtonPressed:(id)sender
{
    [_theTimer invalidate];
}

- (IBAction)resetButtonPressed:(id)sender
{
    if (_theTimer)
    {
        [_theTimer invalidate];
        _theTimer = [self createTimer];
    }

    _currentTimeInSeconds = 0;

    self.timeLabel.text = [self formattedTime:_currentTimeInSeconds];
}

@end

再次感谢任何可以提供帮助的人!

【问题讨论】:

  • 对不起@troop231,我想我不小心把你的编辑搞砸了。随时再次提出建议;)
  • 不是 IOS 编码员,但试图从 'int seconds' 获得百分之一秒似乎注定要失败。
  • 我认为这一行是错误的:int percentths = totalSeconds % 60;因为60应该是100,然后剩下的(秒,分钟等)也需要调整。
  • 您的问题是您假设您的秒数存储在“_currentTimeInSeconds”中。但是,您的计时器设置为每 0.01 秒(= 10 毫秒)触发一次,因此您在 Ivar 中计数的值不是您期望的值。 >> 你期望:秒。你得到:(值 * 10)毫秒

标签: ios objective-c nstimer


【解决方案1】:

首先,您应该将变量的名称从 _currentTimeInSeconds 更改为 _currentTimeInHundredths(如果需要,也可以更短)。

接下来,您需要更新 - (NSString *)formattedTime:(int)totalSeconds 方法中的逻辑。尝试这样的事情(将 totalSeconds 更改为 totalHundredths,原因与之前相同)。

int hours = totalHundredths / 360000;
int minutes = (totalHundredths - (hours * 360000)) / 6000;
int seconds = (totalHundredths - (hours * 360000) - (minutes * 6000)) / 100;
int hundredths = totalHundredths - (hours * 360000) - (minutes * 6000) - (seconds * 100);

我没有对数字进行数学测试,但它们应该是对的。

【讨论】:

  • 另请注意,您可能会在百分之一秒内使用int 遇到溢出问题。您可能需要使用更大的值,具体取决于您希望计时器计数多高。
猜你喜欢
  • 1970-01-01
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
相关资源
最近更新 更多