0

When in my details controller I click this and go back to main controller.

 @IBAction func backButtonClick(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }

Why is not the main function viewDidLoad not hit again?

viewDidLoad()

How to update the main view when going back?

marko
  • 10,684
  • 17
  • 71
  • 92

2 Answers2

4

you need to implement viewDidAppear as viewDidLoad fires only once when the VC is initated

override func viewDidAppear(_animated:Bool) {
  super.viewDidAppear(animated)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 1
    Thanks, that was what I was looking for. – marko May 22 '18 at 18:17
  • I won't say that the answer is not valid at all, however keep in mind that at some point you might face a pretty simple delay for calling `viewDidAppear ` after displaying the view... – Ahmad F May 22 '18 at 18:19
2

Why is not the main function viewDidLoad not hit again?

Because the viewDidLoad() method called when the view controller's view has been loaded, i.e it get called when there is a new allocating for the view controller's view into the memory. Therefore the viewDidLoad won't get called again when getting back (dismissing/popping from the current view controller) to the view controller because it is already loaded, it still in memory.

How to update the main view when going back?

Well, actually viewDidLoad is not the only method for the life cycle of the view controller's view, of course there are other options to achieve what are you looking for. One of the legitimate valid solutions is move the code that should be get called when "going back" from the viewDidLoad into viewWillAppear(_:) method:

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

    // here we go...
}

It get called before displaying the view controller's view, which means that it will get called even in both cases: when presenting/pushing to a view controller and even after dismissing/popping.

Furthermore:

Nevertheless viewWillAppear(_:) is not only the solution for your issue, there are other methods will be get called when "going back" the a view controller, I would suggest to check:

Looking to understand the iOS UIViewController lifecycle

as well as:

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143