假设您使用 Storyboard 进行布局,我在下面编写了一个可能的解决方案。基本上,您保留 aScore 和 cScore 的运行总计,并使用 prepareForSegue 将运行总计传递给下一个视图控制器的 aScore 和 cScore 变量。我创建了一个名为proceedToNextLevel 的函数,每当您想进入下一个级别时都会调用它。
你的 1 级视图控制器看起来像这样:
class Level1ViewController: UIViewController {
var cScore = 0
var aScore = 0
//call this function when you want to proceed to level 2, connect a segue between your level 1 view controller and level 2 view controller give the segue an identifier "ProceedToLevel2Segue"
func proceedToNextLevel() {
performSegue(withIdentifier: "ProceedToLevel2Segue", sender: nil)
}
//pass the accumulated aScore and cScore for level 1 to level 2's aScore and cScore
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! Level2ViewController
destinationVC.cScore = self.cScore
destinationVC.aScore = self.aScore
}
@IBAction func buttonCorrect(_ sender: UIButton)
{
cScore +=1
aScore +=1
correctScore.text = NSString(format: "%i", cScore) as String
attemptScore.text = NSString(format: "%i", aScore) as String
}
@IBAction func buttonIncorrect(_ sender: UIButton)
{
cScore +=0
aScore +=1
correctScore.text = NSString(format: "%i", cScore) as String
attemptScore.text = NSString(format: "%i", aScore) as String
}
}
您的 2 级视图控制器的 aScore 和 cScore 将由 Level1ViewController 中的 prepareForSegue 方法初始化为您在 1 级中的总数。如果它们未初始化,它们默认为 2 级视图控制器中给出的零值。我在 2 级视图控制器中保持增加 aScore 和 cScore 的逻辑相同。
class Level2ViewController: UIViewController {
//these will be initialized to the running total of aScore and cScore from level 1
var cScore: Int!
var aScore: Int!
//proceed to level 3
func proceedToNextLevel() {
performSegue(withIdentifier: "ProceedToLevel3Segue", sender: nil)
}
//the running total for aScore and cScore is passed to level 3
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as! Level3ViewController
destinationVC.cScore = self.cScore
destinationVC.aScore = self.aScore
}
//your scoring logic
@IBAction func buttonCorrect(_ sender: UIButton)
{
cScore +=1
aScore +=1
correctScore.text = NSString(format: "%i", cScore) as String
attemptScore.text = NSString(format: "%i", aScore) as String
}
@IBAction func buttonIncorrect(_ sender: UIButton)
{
cScore +=0
aScore +=1
correctScore.text = NSString(format: "%i", cScore) as String
attemptScore.text = NSString(format: "%i", aScore) as String
}
}
然后您可以使用相同的 segue 技术将最终的 aScore 和 cScore 变量传递给最终的视图控制器并显示您的图表。
注意:如果您希望保存数据,可以使用 Realm 或 Core Data 等本地数据库来保存 aScore 和 cScore。然后,您可以在 prepareForSegue 方法中的视图控制器之间传递已保存对象的主 ID 作为 Int,而不是 aScore 或 cScore,并使用主 ID 在下一个视图控制器中检索分数。