Search code examples
iosswiftxcodeuiviewcontrollerpresentviewcontroller

How to access previous view controller from a dismiss command


Throughout my app I use a navigation controller to push and pop my view controllers. When I pop from one ViewController, I check to see if I can reload the data in the previous one with this:

_ = self.navigationController?.popViewController(animated: true) if let previousViewController = self.navigationController?.viewControllers.last as? AnimalsVC { previousViewController.tableView.reloadData() }

This works every time, but now I need to do the same with another view, but it's not apart of the navigation controller because I modally present (instead of pushing it to the navigation controller). Now there's no way I can access the previous ViewController like before and I can not figure out how to access the previous ViewController.

How can I access the previous ViewController to reload the tableview like the example code without accessing the navigation controller?

I know this is possible with notifications, but I prefer not to use that method if possible!


Solution

  • First of all, It's not necessary to access the previous ViewController to reload tableview(or any other func)

    I recommend you to use Delegate to achieve the same feature.

    Holding a reference to the previous viewController in the way you mentioned will make your app very hard to maintain when your app gets more complicated.