我有一个更新ViewController中两个标签的函数。我怎样才能做到这一点,一旦我切换到这个ViewController,这两个标签都会更新,而不需要用户输入,如按钮?
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var highScoreLabel: UILabel!
func updateScores() {
scoreLabel.text = "\(UserDefaults.standard.integer(forKey: "EndScore"))"
if UserDefaults.standard.string(forKey: "LastGameMode") == "Easy" {
highScoreLabel.text = "\(UserDefaults.standard.integer(forKey: "EasyHighScore"))"
} else if UserDefaults.standard.string(forKey: "LastGameMode") == "Normal" {
highScoreLabel.text = "\(UserDefaults.standard.integer(forKey: "NormalHighScore"))"
} else if UserDefaults.standard.string(forKey: "LastGameMode") == "Hard" {
highScoreLabel.text = "\(UserDefaults.standard.integer(forKey: "HardHighScore"))"
}
}
答案 0 :(得分:1)
您只需覆盖 viewWillAppear
并在其中调用updateScores()
。
您的代码应如下所示:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateScores()
}