如何在20秒后使用swift制作动画? animateWithDuration:delay:没有用 [英] 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")
}
就像显示的代码一样,我想在20秒后打印完成",但是我会立即得到它.
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?
推荐答案
第一种方法:NSTimer
First Method: NSTimer
func myDelayedFunction() {
print("delayed")
}
func myMainFunction() {
let timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "myDelayedFunction", userInfo: nil, repeats: false)
timer.fire()
}
第二种方法:performSelector
Second Method: performSelector
func myDelayedFunction() {
print("delayed")
}
func myMainFunction() {
performSelector("myDelayedFunction", withObject: self, afterDelay: 10)
}
第三种方法:GCD
(如果要使用匿名函数,则很有用)
(改编自此答案)
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")
}
第四种方法:sleep
Fourth Method: sleep
func myMainFunction() {
sleep(10) //This will block whichever thread you're running on.
print("delayed")
}
我倾向于使用第一种方法,因为如果需要,我总是可以使计时器无效(调用timer.invalidate
).不过,每种方法都有其用例.
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.
这篇关于如何在20秒后使用swift制作动画? animateWithDuration:delay:没有用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!