我的应用程序询问用户问题并获得答案,每个问题都有一些固定的时间(例如 30 秒)用于回答。我想向用户显示诸如“最后(n)秒...”之类的警报,并且如果用户在那段时间不回答 - 应用程序应该跳过问题。 使用DispatchQueue编写了一些代码:
let timePerQuestion = 20
let timeStartAlert = 10
for i in (0..<timeStartAlert) {
DispatchQueue.main.asyncAfter(deadline: (.now() + .seconds(timePerQuestion-timeStartAlert+i))) {
self.failureLabel.text = "Left \(Int(timeStartAlert-i)) seconds..."
self.failureLabel.isHidden = false
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(timePerQuestion)) {
self.failureLabel.text = "Reseting question"
self.failureLabel.isHidden = false
self.quiz.skipQuestion()
self.playNewRound()
self.failureLabel.text = "Sorry, that's not it."
}
它可以工作,但是即使用户及时回答问题,这些代码也会执行。 那么,如果用户及时回答,我如何“重置”或“清除”DispatchQueue.main 以防止执行此代码?
最佳答案
那么你必须使用NStimer
类中的scheduled Timer
具体实现如下:
您需要定义一个计时器:
var timer = Timer()//旧版本的 swift 中的 NStimer()
timer = ScheduledTimer(timeInterval: TimeInterval, 调用: NSInitation, 重复: Bool)
其中timeInterval
是执行所需函数之前的时间段,调用
是您要运行的函数,repeats
指示是否希望函数重复调用直到失效。
您可以在 https://developer.apple.com/reference/foundation/timer 中阅读有关 NS 计时器的更多信息。
希望对你有帮助
关于ios - 如何在 Swift 3.0 中一段时间后插入警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40471529/