3

How do i add a delay in Xcode?

self.label1.alpha = 1.0
//delay
self.label1.alpha = 0.0

I'd like to make it wait about 2 seconds. I've read about time_dispatch and importing the darwin library, but i haven't been able to make it work. So can someone please explain it properly step by step?

2

5 Answers 5

7

You only have to write this code:

self.label1.alpha = 1.0    

let delay = 2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
    // After 2 seconds this line will be executed            
    self.label1.alpha = 0.0
}

'2' is the seconds you want to wait

Regards

Sign up to request clarification or add additional context in comments.

Comments

5

This is another option that works -

import Darwin sleep(2)

Then, you can use the sleep function, which takes a number of seconds as a parameter.

2 Comments

Thanks, BK15. For what it's worth, I didn't need to import Darwin because I'm already importing Foundation. I'm using Swift 3, iOS 10, and Xcode 8.
This is so much better than a duplicate answer (for a duplicate question) I found that uses an asynchronous dispatch queue function (which didn't work in some settings).
3

Might be better to use blocks for this one:

self.label1.alpha = 1.0;

UIView animateWithDuration:2.0 animations:^(void) {
    self.label1.alpha = 0.0;
}];

Comments

0

For Swift 5:

self.label1.alpha = 1.0 

let delay : Double = 2.0 //delay time in seconds
let time = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline:time){
    // After 2 seconds this line will be executed
    self.label1.alpha = 0.0
}

This works for me.

Referring to: Delay using DispatchTime.now() + float?

Comments

0

I wouldn't recommend for production, but does the trick

import Foundation 
func block(for t: Double) {
    let group = DispatchGroup()
    group.enter()
    let _ = group.wait(timeout: .now() + t)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.