我有一个函数可以更新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"))"
    }
}

最佳答案

您只需要覆盖viewWillAppear并在其中调用updateScores()
您的代码应该如下所示:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    updateScores()
}

关于ios - 切换到新的ViewController时如何使代码自动运行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46009142/

10-14 15:37