Search code examples
xcodeswiftdelay

Wait/Delay in Xcode (Swift)


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?


Solution

  • 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