Question

I am trying to get a timer to show the counter like this "00:00:00". Here is my current code. I have been trying to get it to work using the stringWithFormat which should be easy but I guess I will have to set up the formats separately. Do you guys have any idea on how to do this?

- (void)TimerCount {
    CountNumber = CountNumber + 1;
    TimerDisplay.text = [NSString stringWithFormat:@"Hour: %0*i", length, hour];
}
Was it helpful?

Solution

- (void)timerCount {

 {
    CountNumber = CountNumber + 1;
    NSInteger seconds = CountNumber % 60;
    NSInteger minutes = (CountNumber / 60) % 60;
    NSInteger hours = (CountNumber / 3600);
    TimerDisplay.text =  [NSString stringWithFormat:@"%i:%02i:%02i", hours, minutes, seconds];
}

Try the above code.

And configure this method to be fired every second.

In viewDidLoad

NSTimer *counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                                        target:self 
                                                      selector:@selector(timerCount) 
                                                      userInfo:nil 
                                                       repeats:YES];
[[NSRunLoop mainRunLoop] addTimer: counterTimer forMode:NSRunLoopCommonModes];

And keep the counterTimer as an iVar to keep it alive until the VC is dealloced, if you are using ARC.

OTHER TIPS

- (void)TimerCount
{
    CountNumber++;
    NSString *time = [[NSString alloc] init];
    NSUInteger seconds = CountNumber;
    NSUInteger minutes = 0;
    NSUInteger hours = 0;
    if (seconds > 59) {
        seconds -= 60;
        minutes++;
        if (seconds < 10) {
            time = [NSString stringWithFormat:@":0%i",seconds];
        } else time = [NSString stringWithFormat:@":%i",seconds];
    }
    if (minutes > 59) {
        minutes -= 60;
        hours++;
        if (minutes < 10) {
            time = [NSString stringWithFormat:@":0%i%@",minutes,time];
        } else time = [NSString stringWithFormat:@":%i%@",minutes,time];
    }
    if (hours < 10) {
        time = [NSString stringWithFormat:@"0%i%@",hours,time];
    } else time = [NSString stringWithFormat:@"%i%@",hours,time];

}

NSString *time is the time.

Also NSTimer to call this method every second:

NSTimer *counterTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                                                        target:self 
                                                      selector:@selector(timerCount) 
                                                      userInfo:nil 
                                                       repeats:YES];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top