我正在开发一个测验应用程序,并具有一个由一系列非按钮组成的stackview。数组中按钮的数量取决于从函数Int
产生的presentQuestion
值,该值由与一个问题相关的答案选择的数量决定(例如:一个问题可以有3个可能的选择,另外2或5,依此类推)。
最初将QuizController
加载到视图层次结构中时,显示的按钮数量正确。但是,一旦用户选择了正确的按钮,就会显示另一个视图控制器,然后用户将回到QuizController
,并且再次加载视图时,将显示错误数量的按钮。
这是初始QuizController的样子(显示正确的按钮数量):
下面是出现第二个问题后QuizController的外观(显示额外的按钮,并显示上一个问题的答案选项):
这是QuizController的代码:
class QuizController: UIViewController {
var questionChoices = [UIButton]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
choicesView.addSubview(buttonStack)
// Function call that presents question
let answer = questionData.presentQuestion(view: choicesView, label: questionLabel, buttons: questionChoices)
var correctAnswer = answer.answerNum
var answerChoices = answer.options
var bCount = answer.buttonCount
// Int variables for customizing buttons
var x = 0
var y = 1
var z = 1
for _ in (1...bCount) {
questionChoices.append(UIButton())
questionChoices[x].translatesAutoresizingMaskIntoConstraints = false
questionChoices[x].layer.cornerRadius = 17.5
questionChoices[x].titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 18)
questionChoices[x].tag = y
if questionChoices[x].tag == correctAnswer {
questionChoices[x].setTitle(answerChoices[0], for: .normal)
print("The right answer is \(questionChoices[x].titleLabel?.text) | button: \(questionChoices[x].tag)")
}
else {
questionChoices[x].setTitle(answerChoices[z], for: .normal)
z += 1
}
print((questionChoices[x].titleLabel?.text)!)
x += 1
y += 1
}
for choice in questionChoices {
buttonStack.addArrangedSubview(choice)
choice.translatesAutoresizingMaskIntoConstraints = false
choice.backgroundColor = UIColor.orange
choice.heightAnchor.constraint(equalTo: self.choicesView.heightAnchor, multiplier: 0.1275).isActive = true
choice.addTarget(self, action: #selector(checkAnswer), for: .touchUpInside)
}
}
}