Search code examples
swiftviewdidload

How to run a function every time a UIViewController is loaded


I have this function :

func setMoneyValues() {
        balanceLabel.text = User.current.roundBalance()
        oweLabel.text = User.current.roundOwed()
        userLabel.text = User.current.roundUser()
    }

that i execute in viewdidload. However, it is only called once, and if I go to another tab (managed by a tab bar controller), change the values, and come back to this page, the values are not updated, because the function is not called again. Anything I can do to make it be called everytime the tab is re-opened?


Solution

  • Perhaps you want it in viewDidAppear, just be advised this is called when a dialog is over the controller and disappears, and also when the user backgrounds and comes back in the app, but given the nature of the code you posted, that's probably where you want it.

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        setMoneyValues()
    }
    

    Also if you want it to update before the view appears, you can change to viewWillAppear it has the same signature otherwise.