Merlin0216
Merlin0216

Reputation: 335

Swift call Function when ViewController is visible

I have a small problem I sadly couldn't solve. I have a few ViewControllers. I need to call a function when going back from a ViewController to the previous ViewController (which does not reload, so viewDidLoad / Appear is not called).

Mustn't there be anything like viewDidLoad, but gets called every time the ViewController is visible?

This is how I open the ViewControllers:

let vc = storyboard?.instantiateViewController(identifier: "levels_vc") as! LevelsViewController
        present(vc, animated: true)

This is the way I try to get the event, but it only gets called the first time (when the ViewController loads the first time), but not when I open a new ViewController from this one and close the new one.

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("VC appeared!")
    }

Upvotes: 1

Views: 2755

Answers (2)

Coder
Coder

Reputation: 553

You can use viewWillAppear or viewDidAppear for that purpose!.

viewWillAppear() is called every time the view will appear on the screen. This can be useful for views that need to be updated every time they’re scrolled to. For example, the Now Playing section in a music app or any view that is updated when it is scrolled to.

viewDidAppear is called when the view has appeared on the users screen. This is a good place to “lazy-load” any other elements onto your screen. If your user interface is very complicated, you don’t want to stall or cause a delay in the previous mentioned methods. It’s better to load something onto the screen and then call some methods to update the views for some large applications.

This is also a create place to start any animations.

Upvotes: 2

Alex
Alex

Reputation: 540

That would be ViewDidAppear() ViewDidAppear() - Apple Developer

Upvotes: 0

Related Questions