我试图用HH创建一个秒表:MM:SS,代码如下:
-(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:ZZZZZZZZ,其中XX是秒。
有人有什么想法?
答案 0 :(得分:6)
你的stringWithFormat要求3个整数,但你只传入一个;)
以下是我之前使用的一些代码,用于执行我认为您正在尝试执行的操作:
- (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]];
}
将它与计时器一起使用,请执行以下操作:
...
[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,你想要每秒计数一次。