2017-09-01 49 views
1

我有一個函數更新ViewController中的兩個標籤。我如何做到這一點,一旦我切換到這個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"))" 
    } 
} 

回答

1

你只需要覆蓋viewWillAppear並調用updateScores()裏面。

您的代碼應該是這樣的:

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

    updateScores() 
} 
相關問題