ios NSTimer - 如何在 Swift 中延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27990085/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:23:05  来源:igfitidea点击:

NSTimer - how to delay in Swift

iosswiftnstimer

提问by Dandy

I have a problem with delaying computer's move in a game.

我有延迟计算机在游戏中移动的问题。

I've found some solutions but they don't work in my case, e.g.

我找到了一些解决方案,但它们在我的情况下不起作用,例如

var delay = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: nil, userInfo: nil, repeats: false)

I tried to use this with function firebut also to no effects.

我试图将它与函数一起使用,fire但也没有任何效果。

What other possibilities there are?

还有哪些可能性?

回答by valfer

Swift 3

斯威夫特 3

With GCD:

使用 GCD:

let delayInSeconds = 4.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {

    // here code perfomed with delay

}

or with a timer:

或使用计时器:

func myPerformeCode() {

   // here code to perform
}
let myTimer : Timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.myPerformeCode), userInfo: nil, repeats: false)

Swift 2

斯威夫特 2

With GCD:

使用 GCD:

let seconds = 4.0
let delay = seconds * Double(NSEC_PER_SEC)  // nanoseconds per seconds
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

dispatch_after(dispatchTime, dispatch_get_main_queue(), {

   // here code perfomed with delay

})

or with a timer:

或使用计时器:

func myPerformeCode(timer : NSTimer) {

   // here code to perform
}
let myTimer : NSTimer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("myPerformeCode:"), userInfo: nil, repeats: false)

回答by eharo2

With Swift 4.2

使用 Swift 4.2

With TimerYou can avoid using a selector, using a closure instead:

WithTimer你可以避免使用选择器,而是使用闭包:

    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (nil) in
        // Your code here
    }

Keep in mind that Timeris toll-free bridged with CFRunLoopTimer, and that run loops and GCD are two completely different approaches.... e

请记住,这Timer是免费桥接的CFRunLoopTimer,并且运行循环和 GCD 是两种完全不同的方法....e

回答by Ramakrishna

In swift we can delay by using Dispatch_after.

在 swift 我们可以延迟使用 Dispatch_after.

SWift 3.0 :-

斯威夫特 3.0 :-

DispatchQueue.main.asyncAfter(deadline: .now()+4.0) {

        alert.dismiss(animated: true, completion: nil)
    }

回答by JSA986