Search code examples
iosswiftuinavigationcontroller

Transferring data back to the root ViewController


in my iOS app the user navigates using a navigation controller. The user navigates using different UITableViewController.

UIViewController - UITableViewController - UITableViewController

After the user has selected an item in the "last" UITableViewController I am using the following call to return to the root view controller:

DispatchQueue.main.async { self.navigationController?.popToRootViewController(animated: true) }

How can I send data back to the root controller? Previously I used notifications, but I really dislike this concept. Is there a more elegant way? Should every single UIViewController on the view-stack implement his own callback which is initialized using the

func prepare(for segue: UIStoryboardSegue, sender: Any?)

method?

How can this be implemented elegantly?


Solution

  • If you are using segues, you could create an unwind segue and use it instead of popToRootViewController. Here you can see how to create an unwind segue.

    Otherwise, based on your hierarchy, before popToRootViewController, you could access your view controller like this:

    if let rootVC = navigationController?.viewControllers.first as? YourViewControllerClass {
        rootVC.someProperty = dataToPass
    }
    navigationController?.popToRootViewController(animated: true)