问题描述
Screen in question 我试图在此处使用viewDidLoad()
函数调用question()
函数一定次数,然后才调用要推送的新视图控制器的代码。但是,两者的代码都在相同的准确时间执行,因此,第一轮结束后,视图控制器就会被推送。我尝试使用不同变体中的循环,但是这些尝试都导致了相似的结果。有想法吗?并预先感谢!
var num1 = Int()
var num2 = Int()
var userInput = 0
@IBAction func numbers(_ sender: UIButton) {
answerLabel.text = answerLabel.text! + String(sender.tag - 1)
userInput = Int(answerLabel.text!)!
answer()
}
override func viewDidLoad() {
super.viewDidLoad()
// Views configuration
question()
}
func answer() {
let answer = num1 + num2
if userInput == answer {
answerLabel.text = ""
viewDidLoad()
let scoreVC = UIStoryboard(name: "Main",bundle: nil).instantiateViewController(identifier: "scoreViewController") as! scoreViewController
self.navigationController?.pushViewController(scoreVC,animated: true)
}
}
func question() {
num1 = Int(arc4random_uniform(100))
num2 = Int(arc4random_uniform(100))
questionLabel.text = "\(num1) + \(num2)"
}
解决方法
在这里我们可以改进的地方很少。我将从基本开始。 由于这些数字一开始是未设置的,所以我们不必分配它们。因此,除了将它们设置为默认值之外,我们还可以将它们保留为Optionals,这使我们可以定义类型并将其保留为以后的赋值。
var num1: Int?
var num2: Int?
现在我们要显示一个问题。事实是,viewDidLoad
仅在视图加载时才使用-顾名思义。因此,我们只需创建一个方法并在其中移动逻辑即可。您已经做到了,我只是将您的函数重命名为一个更具口语的名字
viewDidLoad() {
showNewQuestion()
}
showNewQuestion() { // previously question()
num1 = Int(arc4random_uniform(100))
num2 = Int(arc4random_uniform(100))
questionLabel.text = "\(num1) + \(num2)"
}
到目前为止一切顺利。现在我们要对照Button send函数中的随机值检查输入。除了强制展开(!
)以外,最好还是安全地展开(?
)。
@IBAction func numbers(_ sender: UIButton) {
guard let userInput = answerLabel.text,let userInputAsInt = Int(userInput) else {
return
}
checkAnswer(userInput: userInputAsInt) // previously answere()
}
最后,我们改善了您的answer()
功能。您剩下的事情是计算已经回答了多少个问题。如果我们从不检查程序应该如何知道何时显示分数?要解决此问题,我们记住要问多少个问题(correctAnsweres
,并定义显示分数的时间阈值(showScoreAfter
)
var correctAnsweres = 0
var showScoreAfter = 5
func checkAnswer(userInputAsInt: Int) {
let answer = num1 + num2
if userInputAsInt != answers { // early exit if answered wrong
return
}
correctAnsweres += 1
answerLabel.text = ""
//either show score
if correctAnsweres % ShowScoreAfter == 0 {
let scoreVC = UIStoryboard(name: "Main",bundle: nil).instantiateViewController(identifier: "ScoreViewController") as! ScoreViewController
self.navigationController?.pushViewController(scoreVC,animated: true)
}
// or new Question
else {
showNewQuestion()
}
}