tags:

views:

39

answers:

1

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];
}

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 ??

A: 

Hi,

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.

deanWombourne
Thanks, YY, ZZ, was the format that was being displayed with the above code. But I've changed it to:time.text = [NSString stringWithFormat:@"%02i:%02i:%02i", second/(60*60), second/60, second];based on what you suggest and the format is not HH:MM:SS but my seconds stop counting after 1. Any ideas ?
Stephen
The first line of your method is [time.text intValue] - there isn't an intValue of a string like HH:MM:SS so intValue returns 0 every time. You need to add a variable to your class to store the currentTime. See my edit for some code I've used before to do this.
deanWombourne
All working now, thanks.
Stephen