NSTimer-秒表 [英] NSTimer - Stopwatch
本文介绍了NSTimer-秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用HH:MM:SS创建秒表,代码如下:
I've trying to create a stopwatch with HH:MM:SS, code is as follows:
-(IBAction)startTimerButton;
{
myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(IBAction)stopTimerButton;
{
[myTimer invalidate];
myTimer = nil;
}
-(void)showActivity;
{
int currentTime = [time.text intValue];
int newTime = currentTime + 1;
time.text = [NSString stringWithFormat:@"%.2i:%.2i:%.2i", newTime];
}
尽管输出确实会按预期增加1秒,但输出格式为XX:YY:ZZZZZZZZZZ,其中XX是秒.
Although the output does increment by 1 second as expected the format of the output is XX:YY:ZZZZZZZZ , where XX are the seconds.
任何人有什么想法吗?
Anyone any thoughts ??
推荐答案
您的stringWithFormat要求输入3个整数,但您只传递了一个;)
Your stringWithFormat asks for 3 integers but you're only passing in one ;)
这里有一些我以前使用过的代码来做我认为您要尝试做的事情:
Here is some code that I've used before to do what I think you're trying to do :
- (void)populateLabel:(UILabel *)label withTimeInterval:(NSTimeInterval)timeInterval {
uint seconds = fabs(timeInterval);
uint minutes = seconds / 60;
uint hours = minutes / 60;
seconds -= minutes * 60;
minutes -= hours * 60;
[label setText:[NSString stringWithFormat:@"%@%02uh:%02um:%02us", (timeInterval<0?@"-":@""), hours, minutes, seconds]];
}
要与计时器一起使用,请执行以下操作:
to use it with a timer, do this :
...
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
...
- (void)updateTimer:(NSTimer *)timer {
currentTime += 1;
[self populateLabel:myLabel withTimeInterval:time;
}
其中currentTime是您要每秒计数一次的NSTimeInterval.
where currentTime is a NSTimeInterval that you want to count up by one every second.
这篇关于NSTimer-秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文