我正在开发一个测验应用程序,当你正确回答问题时,它会转向一个视图控制器,如果你按错了答案,它会转移到另一个视图控制器。但是,当我运行模拟器时,如果我点击错误的答案,除倒计时器重置之外没有任何反应。但是如果我点击正确答案那么segues工作正常。这是为什么?
这是我的代码:
import UIKit
class ViewController: UIViewController {
var questionList = [String]()
var counter = 15
var timer = Timer()
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var questionTimer: UILabel!
func updateCounter() {
counter -= 1
questionTimer.text = String(counter)
if counter == 0 {
timer.invalidate()
wrongSeg()
}
}
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
}
let rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]
//matching answer values to go with question keys
var choices = QADictionary[questionList[rand]]!
questionList.remove(at: rand)
//create button
var button:UIButton = UIButton()
//variables
var x = 1
rightAnswerBox = arc4random_uniform(4)+1
for index in 1...4
{
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(choices[0], for: .normal)
}
else {
button.setTitle(choices[x], for: .normal)
x += 1
}
}
randomImage()
}
//dictionary filled with question keys and answer values
let QADictionary = [:]
//wrong view segue
func wrongSeg() {
performSegue(withIdentifier: "incorrectSeg", sender: self)
}
//proceed screen
func rightSeg() {
performSegue(withIdentifier: "correctSeg", sender: self)
}
//Answer Button
@IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox)) {
rightSeg()
timer.invalidate()
print ("Correct!")
}
if counter != 0 {
counter = 15
} else if (sender.tag != Int(rightAnswerBox)) {
wrongSeg()
print ("Wrong!")
timer.invalidate()
questionList = []
}
}
override func viewDidAppear(_ animated: Bool) {
randomQuestion()
questionTimer.text = String(counter)
timer = Timer.scheduledTimer(timeInterval: 1, target:self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)
}
}
答案 0 :(得分:1)
你在buttonAction中输入了错误的条件我已经纠正了它现在检查。如果condiotion
,只需替换其他@IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox)) {
rightSeg()
timer.invalidate()
print ("Correct!")
}/*Here is change*/
else if (sender.tag != Int(rightAnswerBox))
{
wrongSeg()
print ("Wrong!")
timer.invalidate()
questionList = []
}
if counter != 0 {
counter = 15
}
}