Swift中的延迟动作 [英] Delay Actions in Swift
问题描述
我想让活动指示器开始动画,然后在一秒钟后停止。
I want to make an Activity Indicator start animating and then stop after one second.
那么有人知道我该怎么做吗?
So does anyone know how I could do that?
class stuff {
@IBOutlet weak var indicator: UIActivityIndicatorView!
func iGotTriggeredBySomething {
indicator.startAimating()
//delay?
indicator.stopAnimating()
}
}
感谢
推荐答案
dispatch_after()
是延迟动作的标准方法
dispatch_after()
is the standard way of delaying actions.
indicator.startAnimating()
let delay = 4.5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
indicator.stopAnimating()
}
请参阅: dispatch_after -快速启动GCD吗?
为Swift 3.0更新
indicator.startAnimating()
let delay = Int(4.5 * Double(1000))
DispatchQueue.main.after(when: .now() + .milliseconds(delay)) {
indicator.stopAnimating()
}
但是,本着Swift 3.0的精神,我认为扩展 DispatchQueue
是一个更好的解决方案。
However, in the spirit of Swift 3.0, I think extending DispatchQueue
would be a better solution.
extension DispatchQueue {
func delay(_ timeInterval: TimeInterval, execute work: () -> Void) {
let milliseconds = Int(timeInterval * Double(1000))
after(when: .now() + .milliseconds(milliseconds), execute: work)
}
}
这给我们留下了很好的印象
This leaves us with a very nice
indicator.startAnimating()
DispatchQueue.main.delay(4.5) {
indicator.stopAnimating()
}
更新2
深入到Xcode 8.0 beta,我发现 public func +(time:DispatchTime,seconds:Double)-> DispatchTime
。所以,我想这是正确的……
Digging into the Xcode 8.0 beta, I found public func +(time: DispatchTime, seconds: Double) -> DispatchTime
. So, I guess this is valid…
indicator.startAnimating()
DispatchQueue.main.after(when: .now() + 4.5) {
indicator.stopAnimating()
}
我认为没有必要为已经很干净的东西扩展 DispatchQueue
。
I don't think there is a need to extend DispatchQueue
for something this clean already.
-
Swift 3.1更新
Update for Swift 3.1
Swift 3.1有新的语法。他们只是喜欢改变事物而已。
There is new syntax for Swift 3.1. They just likes to change things don't they.
indicator.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 4.5) {
indicator.stopAnimating()
}
这篇关于Swift中的延迟动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!