快速延迟问题

时间:2016-10-04 13:37:34

标签: swift xcode delay

所以我一直致力于创建一个应用程序,如果按下按钮,它会触发 startGame 。然后应该等待我在更改每个图像之前创建的延迟。延迟工作,但他们一启动应用程序就开始,而不是按下按钮。我一直试图修复它。有什么建议吗?

感谢您的帮助!

以下是我认为更重要的代码:

let deadlineTime = DispatchTime.now() + .seconds(1)
let deadlineTime2 = DispatchTime.now() + .seconds(2)
let deadlineTime3 = DispatchTime.now() + .seconds(3)
let deadlineTime4 = DispatchTime.now() + .seconds(4)

@IBAction func startGame(_ sender: AnyObject) {

        trumpImage.isHidden = false

        DispatchQueue.main.asyncAfter(deadline: deadlineTime) {

            self.trumpImage.image = UIImage(named: "trumpTurnOne")

        }

        DispatchQueue.main.asyncAfter(deadline: deadlineTime2) {

            self.trumpImage.image = UIImage(named: "trumpTurnTwo")

        }

        DispatchQueue.main.asyncAfter(deadline: deadlineTime3) {

            self.trumpImage.image = UIImage(named: "trumpTurnThree")

        }

        DispatchQueue.main.asyncAfter(deadline: deadlineTime4) {

                self.runGame()

        }

}

1 个答案:

答案 0 :(得分:0)

试试这个:

let deadlineTime = {return DispatchTime.now() + .seconds(1)}
let deadlineTime2 = {return DispatchTime.now() + .seconds(2)}
let deadlineTime3 = {return DispatchTime.now() + .seconds(3)}
let deadlineTime4 = {return DispatchTime.now() + .seconds(4)}

如果已将四个DispatchTime声明为实例属性,则在生成实例时进行初始值的评估,而不是实际使用这些属性的时间。这意味着DispatchTime.now()表示实例化的时间,可能比用户按下按钮要早得多。

因此,要使DispatchTime.now()表示按下按钮的时间,您可能需要使它们成为计算属性。否则,你需要让它们成为局部变量。

@IBAction func startGame(_ sender: AnyObject) {
    let deadlineTime = DispatchTime.now() + .seconds(1)
    let deadlineTime2 = DispatchTime.now() + .seconds(2)
    let deadlineTime3 = DispatchTime.now() + .seconds(3)
    let deadlineTime4 = DispatchTime.now() + .seconds(4)

    //...
}