我在Swift代码中遇到sleep
函数的问题。我正在使用import Darwin
和usleep(400000)
。达到睡眠之前的一些行动被阻止,我不知道为什么。这里从我的代码很短的例子:Swift中的延迟/睡眠不起作用
@IBAction func Antwort4Button(_ sender: Any) {
if (richtigeAntwort == "4"){
Antwort4.backgroundColor = UIColor.green
Ende.text = "Richtig!"
NaechsteFrage()
}
else {
Ende.text = "Falsch!"
//NaechsteFrage()
}
}
func NaechsteFrage() {
usleep(400000)
Antwort1.backgroundColor = UIColor.red
Antwort2.backgroundColor = UIColor.red
Antwort3.backgroundColor = UIColor.red
Antwort4.backgroundColor = UIColor.red
Ende.text = ""
FragenSammlung()
}
此线将不会执行:
Antwort4.backgroundColor = UIColor.green
Ende.text = "Richtig!"
为什么调用sleep阻止这些行为?如果我删除import Darwin
和sleep
,我的代码工作正常。有没有人有想法?对不起,我的英文不好:P
请勿使用“sleep”或变体。你阻止主线程无所事事。使用['dispatch_after'](https://developer.apple.com/reference/dispatch/1452876-dispatch_after) – jcaron