[英]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. 像所示的代码一样,我想在20秒后打印“完成”,但是我立即得到它。
By the way, how many ways to do make operations delay? 顺便说一下,有多少种方法会使操作延迟?
First Method: NSTimer
第一种方法:
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
第二种方法:
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 ) 第三种方法:
GCD
(如果需要匿名函数很有用) (根据此答案改编)
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
第四种方法:
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
). 我倾向于使用第一种方法,因为如果需要,我总是可以使计时器无效(调用
timer.invalidate
)。 Each method has its use case, though. 不过,每种方法都有其用例。
if you dont actually need to do any animation, can use GCD to accomplish this 如果您实际上不需要做任何动画,可以使用GCD来完成
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(20 * NSEC_PER_SEC)), dispatch_get_main_queue()){
print("finish")
};
you can make a neat little helper function as described in this answer as well 您也可以按照此答案中的说明制作一个简洁的小助手功能
I think, there's a misconception. 我认为这是一个误解。 In your code:
在您的代码中:
UIView.animate(withDuration: 10, delay: 20, options: [], animations: {
// define animations
self.myView.alpha = 0 // as an example
}) { (finish) in
print("finish")
}
the completion handler will be called, when the animation finished. 动画结束时,将调用完成处理程序。 It starts after
delay
seconds (20.0) and takes duration
seconds (10.0). 它在
delay
秒(20.0)之后开始, duration
秒(10.0)。 That is, the animation should be completed after 30 seconds measured from the method call. 也就是说,动画应在从方法调用开始测量的30秒后完成。
(You can place NSLog
statements in your code to see when things happen) (您可以在代码中放置
NSLog
语句以查看何时发生)
I cannot reproduce what you are experiencing, that "finish" will be printed immediately. 我无法复制您正在体验的内容,“完成”将立即打印出来。 However, I can confirm that
UIView.animateWithDuration
works as expected - given the animation block is actually not empty. 但是,我可以确认
UIView.animateWithDuration
可以UIView.animateWithDuration
工作-给定动画块实际上不是空的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.