【问题标题】:Seconds to - Minutes - Hours - Milliseconds秒到 - 分钟 - 小时 - 毫秒
【发布时间】:2012-08-19 13:44:17
【问题描述】:

我正在使用 NSTimer,代码如下:

- (IBAction)start:(id)sender {

    MainInt = 0;

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

}

如何同时显示毫秒和分钟?

没有找到任何简单但有效的方法。

【问题讨论】:

    标签: ios nstimer


    【解决方案1】:

    毫秒使用:

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

    分钟使用:

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

    【讨论】:

    • 使用时间间隔为一毫秒的 NSTimer 对象是否合理?你知道任何讨论这个的文档吗?
    • 如果你以一毫秒的间隔尝试这个,它很可能会错过很多节拍。但是,你真的需要这么小的间隔吗?如果您每 50 毫秒刷新一次显示,用户将无法区分。 (如果您希望显示的数字不是零,则只需使用奇数间隔,例如 53 毫秒。)
    • 我只是对这种可能性感兴趣,感谢您的回复。
    【解决方案2】:

    缩短间隔,例如 0.1f timer = [NSTimer scheduleTimerWithTimeInterval:0.1f target:self selector:@selector(countup)userInfo:nil repeats:YES]; 并使用NSDateFormatter 显示计数器。 NSDateFormatter 的示例可以在这里找到: timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup)userInfo:nil repeats:YES];

    这里很好地解释了 NSDateFormatter 的工作原理:How to handle different date time formats using NSDateFormatter

    你的计时器应该更新一个浮点变量,它存储毫秒。

    示例:

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"mm:ss:SSS"];
        NSTimeInterval interval = [startDate timeIntervalSinceNow]*-1;
        NSString *clock = [formatter stringFromDate:[NSDate dateWithTimeInterval:interval sinceDate:startDate]];
    

    但你应该去 Roy Sharon 回答。

    【讨论】:

    • 你能解释一下 NSDateFormatter 吗?
    • 你能举个例子吗?
    猜你喜欢
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    相关资源
    最近更新 更多