Search code examples
iosswiftuinavigationcontrollerviewcontroller

how to check if a view controller appeared after some other page in navigation controller pressed back button?


I'm in detailViewController and when I press back button, it goes to mainViewController. How can it be determined in mainViewController that it was not freshly loaded but the back button was pressed in detailViewController?

There is a table which I want to reload in mainViewController and hence I'm trying to determine if it was loaded freshly or coming from detailViewController. Any help would be greatly appreciated and up voted. Thank you.


Solution

  • Override the viewWillAppear() function in your mainViewController to execute tasks before loading it.

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated: animated)
    
        //do tasks when coming from detailViewController
    }
    

    EDIT:

    There is another way if you don't want the code in viewWillAppear to ecexute upon fresh load, but i don't know if it's the best thing to do. In your back button handler do the following:

    //pop the detailViewController
    self.navigationController.popViewControllerAnimated(true)
    
    //mainViewController is now at the top
    //safely unpack it
    if let parentVC = self.navigationController.topViewController as? mainViewController {
        //call a custom function in mainViewController which will
        //execute only the stuff you want upon back button press
    
        parentVC.customFunction()
    }