计时器在第一次测验Swift 3后走得太快

时间:2017-01-10 10:45:25

标签: swift

我有测验应用程序,每个问题有10秒计时器。第一个问题计时器很好,但在第二个问题,它比以前更快。我尝试this教程制作计时器和this教程来制作测验应用

这是我的代码:

override func viewDidLoad() {
timerBegin()
}

func timerBegin() {
    myTimer.invalidate() // print error `fatal error: unexpectedly found nil while unwrapping an Optional value`
    timeLeft = 10
    myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SoalViewController.timerRunning), userInfo: nil, repeats: true)
}

func timerRunning() {
    timeLeft -= 1
    timeLabel.text = "\(timeLeft)"
    if timeLeft == 0 {
        myTimer.invalidate()
        timeLabel.text = "10"
        pickQuestion()
        timerBegin()
    }
}

这是我的选项按钮代码:

@IBAction func opsiA(_ sender: Any) {
    timeLabel.text = "10"
    timerBegin()
    if AnswerNumber == 0 {
        pickQuestion()
        Score += 10
        scoreLabel.text = "\(Score)"
    } else {

        pickQuestion()
        print("Wrong")
    }
}
@IBAction func opsiB(_ sender: Any) {
    timeLabel.text = "10"
    timerBegin()
    if AnswerNumber == 1 {
        pickQuestion()
        Score += 10
        scoreLabel.text = "\(Score)"
    } else {
        pickQuestion()
        print("Wrong")
    }
}
@IBAction func opsiC(_ sender: Any) {
    timeLabel.text = "10"
    timerBegin()
    if AnswerNumber == 2 {
        pickQuestion()
        Score += 10
        scoreLabel.text = "\(Score)"
    } else {
        pickQuestion()
        print("Wrong")
    }
}
@IBAction func opsiD(_ sender: Any) {
    timeLabel.text = "10"
    timerBegin()
    if AnswerNumber == 3 {
        pickQuestion()
        Score += 10
        scoreLabel.text = "\(Score)"
    } else {
        pickQuestion()
        print("Wrong")
    }
}

这是我的挑选问题功能:

func pickQuestion() {
    if Questions.count > 10 {

        QNumber = Int(arc4random_uniform(UInt32(10)))
        textView.text = Questions[QNumber].Question
        AnswerNumber = Questions[QNumber].Answer
        for i in 0..<Buttons.count {
            Buttons[i].setTitle(Questions[QNumber].Answers[i], for: UIControlState.normal)
        }
        Questions.remove(at: QNumber)
    } else {
        darkView.isHidden = false
        scoreLabel.text = "\(Score)"
        timeLabel.isHidden = true
        if Score > standStill {
            HighScore = Score
            highScoreLabel.text = NSString(format: "Highscore : %i", HighScore) as String
            let currentHighScore = UserDefaults.standard
            currentHighScore.set(HighScore, forKey: "HighScore")
        } else {
            let currentHighScore = UserDefaults.standard
            currentHighScore.set(standStill, forKey: "HighScore")
        }
    }

}

我已经尝试通过在timerBegin函数的第一行添加myTimer.invalidate()来停止计时器,但它会打印fatal error: unexpectedly found nil while unwrapping an Optional value

0 个答案:

没有答案