swift - Swift 计时器未遵循正确的时间间隔
问题描述
我正在尝试创建一个测验应用程序,它在计时器到期时(即 10 秒,我希望Timmer
有 1 秒的间隔)为每个问题设置一个计时器,它会自行重置并获取下一个问题并Timmer
再次从 10.. . 但我的问题是,当第一个问题被加载时,计时器没有遵循固定的时间间隔,它显示的时间间隔为 2 ... 即 10,8,6 .. 然后对于第二个问题,它会跳转 3 秒的时间间隔,类似地间隔增加。
var countTime = 10.0
func handleNextQuestion() throws {
nextQuestion()
if questionCounter == allQuestions.list.count-1{
finishButton.isHidden = false
nextButton.isHidden = true
//scoreLbl.text = "\(score)"
}
}
func nextQuestion(){
showResultView(isCorrect: (question?.isAnswerCorrect)!)
questionCounter = questionCounter + 1
question = fetchQuestion()
setQuizView(question: question!)
}
@objc func update() {
if(countTime > 0) {
countTime = countTime - 1
self.countDownLabel.text = String(countTime)
}else{
timer.invalidate()
countTime = 10.0
do{
try handleNextQuestion()
}
catch{
moveToResultView()
}
}
}
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)
}
func setQuizView(question:Question) {
self.countDownLabel.text = "10"
startTimer()
startTimer()
questionLabel.text = question.questionText
ansLbl1.text = question.answer1
ansLbl2.text = question.answer2
ansLbl3.text = question.answer3
ansLbl4.text = question.answer4
if question.selectedAnswer == Constants.DEFAULT_ANSWER {
for checkBoxItem in checkBoxlist{
checkBoxItem.isChecked = false
}
}
}
解决方案
func setQuizView(question:Question)
调用startTimer()
两次。我认为这解释了这种行为。在每个新问题上,计时器都会启动两次,但只会失效一次,因此秒数会增加一个额外的问题。
只需删除其中一个调用startTimer()
推荐阅读
- jquery - 在切换按钮中执行简码
- c# - 自定义身份验证中间件 - 如何检查请求是匿名的还是授权的?
- javascript - 反应待办事项列表过滤器
- amazon-web-services - 资源策略中的 AWS NotPrincipal 导致 AccessDeniedException
- python - 当我从命令行运行 Python 时,我应该如何接受这个文本文件?
- reactjs - React 将子组件放置在父组件中
- docker - MLflow Kubernetes Pod 部署
- php - 将 dataProviders 数据传递给设置 [PHPUnit]
- xml - 在 DOCTYPE XSLT 2.0 Saxon9he 中插入 ENTITY 声明
- c++ - 读取 Json 来反对