简体   繁体   English

NSTimer - 如何在Swift中延迟

[英]NSTimer - how to delay in Swift

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, eg 我找到了一些解决方案,但它们在我的情况下不起作用,例如

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

I tried to use this with function fire but also to no effects. 我尝试使用它与功能fire但也没有效果。

What other possibilities there are? 还有哪些其他可能性?

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)

With Swift 4.2 使用Swift 4.2

With Timer You can avoid using a selector, using a closure instead: 使用Timer您可以避免使用选择器,而是使用闭包:

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

Keep in mind that Timer is toll-free bridged with CFRunLoopTimer , and that run loops and GCD are two completely different approaches.... e 请记住, Timer使用CFRunLoopTimer进行免费桥接,并且运行循环和GCD是两种完全不同的方法....

In swift we can delay by using Dispatch_after. 在swift中,我们可以通过使用Dispatch_after.来延迟Dispatch_after.

SWift 3.0 :- SWIFT 3.0: -

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM