我的应用程序询问用户问题并得到答案,每个问题都有一些固定的时间(例如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."
}
它有效,但即使用户及时回答问题,这些代码也会执行。 所以我怎么能重置&#34;或&#34;清除&#34;如果用户及时回答,DispatchQueue.main是否阻止执行此代码?
答案 0 :(得分:0)
您必须使用课程scheduled Timer
NStimer
实施如下:
你需要定义一个计时器:
var timer = Timer()//NStimer()in older versions of swift
timer = scheduledTimer(timeInterval: TimeInterval, invocation: NSInvocation, repeats: Bool)
其中timeInterval
是执行所需函数之前的时间段,invocation
是您要运行的函数,repeats
表示您是否希望函数重复调用直到无效。
您可以在https://developer.apple.com/reference/foundation/timer
中详细了解NS计时器我希望它有所帮助
答案 1 :(得分:0)
最好使用bool变量的数组/字典来解决这类问题。
您可以拥有以下示例中给出的数组或字典。
var questionAnswered: [String: Bool] = ["1" : false, "2" : false, "3" : false, "4" : false, "5" : false]
此处Key = question id
和Value = a boolean indicating whether it is answered
。您可以根据用户是否回答特定问题来更新它。然后,您可以通过以下方式在代码中使用它:
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(timePerQuestion)) {
if let answered: Bool = self.questionAnswered[questionID] {
if !answered {
DispatchQueue.main.async {
self.failureLabel.text = "Reseting question"
self.failureLabel.isHidden = false
self.quiz.skipQuestion()
self.playNewRound()
self.failureLabel.text = "Sorry, that's not it."
}
}
}
}
随意建议编辑以使其更好:)