Reputation: 1982
I have a UILabel that I would like to update. It has been added to the class by ctrl-cicking and adding through the XIB file. Im trying to update the label text after waiting for a short delay. As of now, there is nothing else going on except for the code below. Howver when I run this, the simulator blanks out for a moment and takes me straight to the last updated text. It doesnt show me the 100
just the 200
.
How do I get the label to update like I want it to. Ultimately Im trying to have a timer of sorts decrement inside the label.
Label linked from the XIB to header file:
@property (strong, nonatomic) IBOutlet UILabel *timeRemainingLabel;
In Implmentation:
- (void)viewDidLoad
{
[super viewDidLoad];
self.timeRemainingLabel.text = @"100";
sleep(1);
self.timeRemainingLabel.text = @"200";
}
It has been synthesized.
XCode 4.3.2, Mac OSX 10.7.3, iOS Simulator 5.1 (running iPad), iOS 5
Upvotes: 2
Views: 887
Reputation: 11145
It will never show you 100 like this because you are using sleep
here which is stopping the execution of your program and just after 1 sec of sleep
you are updating the text. If you want to do this then you can use an NSTimer
for this.
Change your above code like this:
- (void)viewDidLoad
{
[super viewDidLoad];
self.timeRemainingLabel.text = @"100";
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(updateLabel) userInfo:nil repeats:NO];
}
- (void) updateLabel
{
self.timeRemainingLabel.text = @"200";
}
Upvotes: 3
Reputation: 726987
The problem with your implementation is that the execution sequence does not leave the method while in the sleep
. This is the problem, because the UI subsystem never gets a chance to update the label to the "100"
value before it gets a command to set it to "200"
.
To do this correctly, first you need to create a timer in your init method, like this:
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateLabel) userInfo:nil repeats: YES];
Then you need to write the code for your updateLabel
method:
-(void) updateLabel {
NSInteger next = [timeRemainingLabel.text integerValue]-1;
timeRemainingLabel.text = [NSString stringWithFormat:@"%d", next];
}
Upvotes: 3
Reputation: 7644
Your view doesn't appear till the view hasn't loaded and the text of the label timeRemainingLabel
is @"200"
when that happens. So you do not see the text changing. Use an NSTimer
to do this instead and assign the text to the label in the selector:
timer = [NSTimer scheduledTimerWithTimeInterval:timeInSeconds target:self selector:@selector(updateText) userInfo:nil repeats: YES/NO];
and in your update method, set the latest text as per your requirement:
-(void) updateText {
self.timeRemainingLabel.text = latestTextForLabel;
}
Upvotes: 1