我的应用程序询问用户问题并得到答案,每个问题有一些恒定的时间(例如30秒)来回答。我想要显示用户警告像“最后(n)秒......”,如果用户不会在那个时候回答 - 应用程序应该跳过问题。 写了一些代码,使用DispatchQueue:在Swift 3.0中如何插入提醒一段时间
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,以防止在用户及时回答时执行此代码?
只要把你的条件,即。 'if!userHasAnswered {...}',在块内部。 – Connor
如果gcd使用计时器,并且用户回答问题时使计时器无效。 –
它看起来像不可能使用(userHasAnswered)变量,因为它会因不同的问题而不同(某些问题及时回答,有些会被跳过)。如何使用计时器? – zzheads