ibirdbluer ibirdbluer - 7 months ago 28
Swift Question

How to do animation in 20 seconds later using swift? animateWithDuration:delay: is useless

UIView.animateWithDuration(10, delay: 20, options: .TransitionNone, animations: {

}) { (let finish) in
print("finish")
}


Like the code shown, i want to print "finish" after 20 seconds, however i get it immediately.

By the way, how many ways to do make operations delay?

Answer

First Method: NSTimer

func myDelayedFunction() {
    print("delayed")
}

func myMainFunction() {
    let timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "myDelayedFunction", userInfo: nil, repeats: false)
    timer.fire()
}

Second Method: performSelector

func myDelayedFunction() {
    print("delayed")
}

func myMainFunction() {
    performSelector("myDelayedFunction", withObject: self, afterDelay: 10)
}

Third Method: GCD (useful if you want an anonymous function) (adapted from this answer)

let delayInSeconds: Int64 = 3
let popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * Int64(NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue()) {
    print("Delayed") 
}

Fourth Method: sleep

func myMainFunction() {
    sleep(10) //This will block whichever thread you're running on.
    print("delayed")
}

I tend to use the first method, because I can always invalidate the timer if I need to (calling timer.invalidate). Each method has its use case, though.