ios swift中的延迟功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28821722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delaying function in swift
提问by CoolMAn
I don't have a code to sample or anything, because I have no idea how to do it, but can someone please tell me how to delay a function with swift for a set amount of time?
我没有要采样的代码或任何东西,因为我不知道该怎么做,但是有人可以告诉我如何使用 swift 延迟一段时间的功能吗?
回答by Farlei Heinen
You can use GCD (in the example with a 10 second delay):
您可以使用 GCD(在示例中延迟 10 秒):
Swift 2
斯威夫特 2
let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.functionToCall()
})
Swift 3 and Swift 4
斯威夫特 3 和斯威夫特 4
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
回答by Anand
Swift 3 and AboveVersion(s) for a delay of 10 seconds
Swift 3 及以上版本延迟 10 秒
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
self.functionToCall()
}
回答by JChomali
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)
This would call the function functionHere() with a 3 seconds delay
这将调用函数 functionHere() 延迟 3 秒
回答by KorinW
For adding argument to delay function.
用于向延迟函数添加参数。
First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.
首先设置一个字典,然后将其添加为 userInfo。以计时器为参数展开信息。
let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)
Then in the called function
然后在被调用的函数中
func functionHereWithArgument (timer : NSTimer)
{
if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
{
let argumentInt : Int = (userInfo[argumentInt] as! Int)
}
}