【发布时间】: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