I want to change my UILabel
's text after 2 seconds.
I tried setting my UILabel
's text to "A text", and use sleep(2)
and finally changing the text to "Another text".
But sleep(2)
only freezes the app and "Another text" is set without displaying "A text" for 2 seconds.
How may I display "A text" for 2 seconds and then show "Another text"?
I know I am late to this party. But I found people haven't mention thread sleep. If you are using GCD to call that function. You can use :
to delay the thread for 2 seconds.
Edit 2 (Feb 2015):
I think the NSTimer is a great solution. My solution just giving another option to achieve the goal of NSTimer.
Please read: How do I use NSTimer?
In the class, you need this method:
Edit 3 (May 2016):
In Swift 2.0, you can use this way:
It creates an NSTimer's entity and adds the timer automatically to the NSRunLoop associated with the NSThread in which the timer is created.
Edit 4 (Jun 2016):
In Swift 2.2, the way to invoke select is:
So, it is something like:
Edit 5 (Oct 2016):
In Swift 3, the way to invoke select is:
So, it is something like:
Then, the func should looks like this:
Edit 6 (May 2018):
In Swift 4, we can do as below way.
Then, the func should looks like this:
Grand Central Dispatch has a helper function
dispatch_after()
for performing operations after a delay that can be quite helpful. You can specify the amount of time to wait before execution, and thedispatch_queue_t
instance to run on. You can usedispatch_get_main_queue()
to execute on the main (UI) thread.In Swift 3, the above example can be written as:
You need to use a timer. Using sleep will halt your entire program. Check NSTimer
You can accomplish this with a timer, e.g.
This is because the view isn't updated until the end of the runloop. Instead of using sleeps try using NSTimer to set a specific time to update the view.
You can use
NSTimer
, like so -Define another method
updateLabel
and do the updation there. Define your timeInterval to suite your needs...Also setting
repeats
toYES
makes sure that this selector is executed every 0.5 seconds (in the above case).