Dyllan
Dyllan

Reputation: 21

How To Have A Delay When Changing UILabel Text

I have got 3 empty UILabels on the screen and I am changing their text programmatically. I want to have a delay of 1.5 and 2 seconds... For example, first one pops up, 1 second delay, second one pops up, 1.5 second delay, third one pops up, 2 second delay.

I have written the lines of code to change the text already but they all pop up at the same time. sleep(); doesn't work properly.

load1.text = @"Reading fingerprint...";

load2.text = @"Fingerprint read...";

load3.text = @"Determining result...";

That is the code I'm using to change the text. It happens when I press a button.

Thanks in advance...

Upvotes: 2

Views: 917

Answers (1)

rmaddy
rmaddy

Reputation: 318954

There are a few approaches. One is to use dispatch_after:

// Show first now
load1.text = @"Reading fingerprint...";

// Show second after 1 second
int64_t delayInSeconds = 1.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    load2.text = @"Fingerprint read...";
});

// Show third after 2.5 seconds
delayInSeconds = 2.5;
popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    load3.text = @"Determining result...";
});

Of course it seems like it would be better to show the updated labels after each of those steps are actually completed instead of the artificial delays. Wouldn't it?

Upvotes: 4

Related Questions