Reputation: 531
I'm using an NSTimer to update a countdown label every second ("5 seconds ..." then "4 seconds ... " etc) but each time the label is updated, it overwrites the previous output:
This is the method for updating the label, which will run every second until the 5-second countdown ends:
- (void)timerRun {
UILabel *test = [[UILabel alloc] init];
test.text = [NSString stringWithFormat:@"%d seconds", secondsCount];
[self.audioPicker.view addSubview:test];
if (secondsCount == 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
secondsCount = secondsCount - 1;
}
I've tried setting the label back to nil or blank at the beginning of the loop, but I'm clearly doing something wrong. How do I make it so the labels don't overwrite each other like this?
Upvotes: 1
Views: 754
Reputation: 79
create a label outside of timerRun
only update the text inside of the method
// make sure the label is initialed before use
@property (strong, nonatomic) UILabel *test;
- (void)timerRun {
test.text = [NSString stringWithFormat:@"%d seconds", secondsCount];
if (secondsCount == 0) {
[countdownTimer invalidate];
countdownTimer = nil;
}
secondsCount = secondsCount - 1;
}
Upvotes: 1
Reputation: 2451
do like this
UILabel *test ;// instance variable
-(void)viewDidLoad
{
text = [[UILabel alloc]initWithFrame:CGRectMake(50.0,200.0, 150.0,200.0)];// use your frame dimensions
test.text = [NSString stringWithFormat:@"%d seconds", secondsCount];
[self.audioPicker.view addSubview:test];
}
- (void)timerRun
{
test.text = [NSString stringWithFormat:@"%d seconds", secondsCount];
if (secondsCount == 0)
{
[countdownTimer invalidate];
countdownTimer = nil;
}
secondsCount--;
}
Upvotes: 1
Reputation: 126
Create label outside of timerRun method as it keeps on creating label as timerRun is called
Upvotes: 1
Reputation: 45500
Dont create the label inside of your method.
This will create a label at each call.
Instead declare it at the class level
Upvotes: 1