NSTimer - Stopwatch
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];
}
Alth开发者_StackOverflow中文版ough 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 ??
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;
}
where currentTime is a NSTimeInterval that you want to count up by one every second.
精彩评论