本文介绍了Swift中的延迟/睡眠不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift代码中的 sleep 函数遇到问题。我正在使用导入达尔文 usleep(400000)。入睡前的某些动作被阻止,我不知道为什么。这是我代码中的简短示例:

I have a problem with the sleep function in Swift code. I'm using import Darwin and usleep(400000). Some actions before reaching the sleep are blocked and I dont know why. Here a short example from my code:

@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!"

为什么叫睡眠阻止了这些动作?如果删除导入Darwin sleep ,我的代码可以正常工作。有人知道吗?对不起,我的英语不好:P

Why is calling sleep blocking these actions? If I delete the import Darwin and the sleep, my code works fine. Has anyone an idea? Sorry for my bad english :P

推荐答案

其他alrady回答了这个问题,我只想提供一些其他信息(尚无法评论) )。

Others alrady answered the question, I just wanted to provide some additional information (cannot comment yet).

您说 Antwort4.backgroundColor = UIColor.green 未执行。为了澄清起见,这是执行的,但是由于调用 sleep 会阻塞用户界面,因此看不到结果。这就是发生的情况:

You said that Antwort4.backgroundColor = UIColor.green is not executed. To clarify, this is executed, but you don't see the result becuase you call sleep, which is blocking the UI. Here is what happens:


  1. Antwort4 的背景颜色设置为绿色

  2. 睡眠:阻止UI阻止应用程序实际显示绿色背景

  3. 将背景颜色设置为 Antwort4 重新变红

  1. set background color of Antwort4 to green
  2. sleep: block the UI which prevents the app from actually showing the green background
  3. set the background color of Antwort4 to red again

要解决当前的问题,您可以使用苹果 API。因此,您可以使用:

To solve the problem at hand you can use Apples Displatch API. So instead of sleept, you could use:

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    self.Antwort1.backgroundColor = UIColor.red
    self.Antwort2.backgroundColor = UIColor.red
    self.Antwort3.backgroundColor = UIColor.red
    self.Antwort4.backgroundColor = UIColor.red

    self.Ende.text = ""

    self.FragenSammlung()
}

这篇关于Swift中的延迟/睡眠不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 23:30