问题描述
好的,所以我在此基于本教程中的秒表应用程序代码 http://iphonedev.tv/blog/2013/7/7/getting-started-part-3-adding-a-带nstimer的秒表和我们的头等舱我喜欢它的设置方式,但我不知道如何增加百分之一秒,有人知道怎么做吗?
Ok, so I've based my stopwatch app code from this tutorial right here http://iphonedev.tv/blog/2013/7/7/getting-started-part-3-adding-a-stopwatch-with-nstimer-and-our-first-classI like the way it is set up, but I can't figure out how to add hundredths of a second to it, anyone know how to do this?
我的 ViewController.m 文件
My ViewController.m file
#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
再次感谢任何可以提供帮助的人!
Thanks again for anybody who can help!
推荐答案
首先,您应该将变量的名称从 _currentTimeInSeconds
更改为 _currentTimeInHundredths
(如果你想要).
First, you should change the name of your variable from _currentTimeInSeconds
to _currentTimeInHundredths
(or something shorter if you want).
接下来,您需要更新 - (NSString *)formattedTime:(int)totalSeconds
方法中的逻辑.尝试类似的操作(出于与之前相同的原因,将 totalSeconds 更改为 totalHundredths).
Next, you need to update the logic in your - (NSString *)formattedTime:(int)totalSeconds
method. Try something like this (changing totalSeconds to totalHundredths for the same reason as before).
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);
我还没有测试数字的数学,但它们应该是正确的.
I haven't tested the math on the numbers, but they should be right.
这篇关于如何向秒表应用程序添加毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!