As in most games i hv seen the timer in a format "01:05"
I m trying to implement a timer, and on reset i need to reset the timer to "00:00".
This timer value should be in label.
How to create a timer which is incrementing? like 00:00---00:01---00:02..........somthing like dat.
suggestions
regards
A Simple way I've used is this:
//In Header
int timeSec = 0;
int timeMin = 0;
NSTimer *timer;
//Call This to Start timer, will tick every second
-(void) StartTimer
{
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
//Event called every time the NSTimer ticks.
- (void)timerTick:(NSTimer *)timer
{
timeSec++;
if (timeSec == 60)
{
timeSec = 0;
timeMin++;
}
//Format the string 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
//[timeLabel setStringValue:timeNow];
timeLabel.text= timeNow;
}
//Call this to stop the timer event(could use as a 'Pause' or 'Reset')
- (void) StopTimer
{
[timer invalidate];
timeSec = 0;
timeMin = 0;
//Since we reset here, and timerTick won't update your label again, we need to refresh it again.
//Format the string in 00:00
NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];
//Display on your label
// [timeLabel setStringValue:timeNow];
timeLabel.text= timeNow;
}
This should give you a timer that is fairly accurate, atleast to the naked eye. This does not refresh the view, only updates the time and label:
//call this on reset. Take note that this timers cannot be used as absolutely correct timer like a watch for example. There are some variation.
-(void) StartTimer
{
self.startTime = [NSDate date] //start dateTime for your timer, ensure that date format is correct
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTick:) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
-(void) timerTick
{
NSTimeInterval timeInterval = fabs([self.startTime timeIntervalSinceNow]); //get the elapsed time and convert from negative value
int duration = (int)timeInterval; // cast timeInterval to int - note: some precision might be lost
int minutes = duration / 60; //get the elapsed minutes
int seconds = duration % 60; //get the elapsed seconds
NSString *elapsedTime = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds]; //create a string of the elapsed time in xx:xx format for example 01:15 as 1 minute 15 seconds
self.yourLabel.text = elapsedTime; //set the label with the time
}
create an object of NSDate type e.g.'now'. After that follow the code below:
self.now = [NSDate DAte];
long diff = -((long)[self.now timeIntervalSinceNow]);
timrLabel.text = [NSString stringWithFormat:@"%02d:%02d",(diff/60)%60,diff%60];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With