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?

ChubbyChocolate
  • 236
  • 2
  • 3
  • 13
  • 2
    possible duplicate of [How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?](http://stackoverflow.com/questions/4139219/how-do-you-trigger-a-block-after-a-delay-like-performselectorwithobjectafter) – zoul Aug 31 '15 at 17:24
  • See the answer here: http://stackoverflow.com/a/24318861/2538939 – Code Different Aug 31 '15 at 17:29

4 Answers4

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

Adagio
  • 645
  • 10
  • 18
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.

Alex Hall
  • 806
  • 9
  • 16
BK15
  • 729
  • 1
  • 6
  • 11
  • 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. – Josh Adams Oct 10 '16 at 17:04
  • 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). – Alex Hall Jul 10 '17 at 19:37
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;
}];
Choppin Broccoli
  • 2,930
  • 2
  • 17
  • 27
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?