Reputation:
I am trying to make a count down label, But it is not getting decremented..Can any one spot out the error in code
- (IBAction)start:(id)sender
{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
-(void) updateCountdown
{
int hours, minutes, seconds;
int secondsLeft = 30;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
Upvotes: 1
Views: 857
Reputation: 117
You can declare secondsLeft
and timer
as ivars, decrement secondsLeft
every time updateCountdown
is called and invalidate the timer
when there are no seconds left to decrement.
- (IBAction)start:(id)sender
{
secondsLeft = 30;
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}
- (void) updateCountdown
{
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
secondsLeft--;
if (seconds==0)
{
[timer invalidate];
}
}
Upvotes: 3
Reputation:
I found the problem...
-(IBAction)start:(id)sender{
countDownView.hidden=NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateElapsedTime) userInfo:nil repeats:YES];
secondsLeft=30;
}
-(void) updateCountdown {
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
Upvotes: 0
Reputation: 681
Because each time when timer fires you use same value for seconds
int secondsLeft=30;
You must set value for secondsLeft on starting Timer and decrement it on timer
- (IBAction)start:(id)sender{
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
secondsLeft=30;
}
-(void) updateCountdown {
int hours, minutes, seconds;
secondsLeft--;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
Upvotes: 6
Reputation: 664
You have assigned int secondsLeft=30;
in your updateCountdown
method that's normal.
You should set the initial value of secondLeft somewhere else and then in your method updateCountdown
you need to decrement it's value
-(void) updateCountdown {
int hours, minutes, seconds;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
if (secondsLeft > 0) secondsLeft--;
}
Upvotes: 1