1

Consider three different controllers A, B and C where A is initial controller in Navigation Controller.

Now I push to B and then push to C.

A --> B --> C

Then I want to go from C to A. How can I go there with a single push and animation. I guess the way would be finding the controller A from the navigation stack and call popToController method. Let me know If any other better way.

Now main question is how can I pass the data from C --> A. If it's from B --> A I could use the delegation. But for C --> A what could be done to use the delegation?

I do have workaround by using observer, singleton, reactive patterns. But I would like to know if any better way can be used.

Parth Adroja
  • 13,198
  • 5
  • 37
  • 71
  • self.navigationController?.popToRootViewController(animated: true) – Jay Patel Feb 22 '18 at 09:28
  • If you want to pass data with delegate from c-> a then you can create two protocols one will pass data from c->b and other will pass data from b->a. Why? Because your A has ref of B not of C (A is pushing B); so you can't directly call delegate from c->a – Prashant Tukadiya Feb 22 '18 at 09:40
  • Use this [link](https://stackoverflow.com/a/15839298/5391914) for unwinding to your A view controller – Hamed Feb 22 '18 at 09:49

3 Answers3

1

You can have multiple ways to achieve this functionality. Once can be get you VC from list and pop to it.

let viewControllers: [UIViewController] = self.navigationController!.viewControllers ;
    for aViewController in viewControllers {
        if let controllerA =  aViewController as? AViewController) {
           controllerA.data = self.data               
           self.navigationController?.popToViewController(controllerA, animated: true);
        }
    }

Also you might be interested in unwind segue. Here is a nice example too.

CZ54
  • 5,488
  • 1
  • 24
  • 39
Saad Chaudhry
  • 1,392
  • 23
  • 37
0

You can achieve this via this approach, it will work 100%

for item in self.navigationController?.viewControllers ?? [UIViewController]() {
        if item is FirstVC, let vc = item as? FirstVC {
            vc.data = ThirdVC.data //3rd vc data assign to 1st vc
            vc.callAnyMethodOfFirstVC()
            self.navigationController?.popToViewController(item, animated: true)
        }
    }
Purnendu roy
  • 818
  • 8
  • 15
-3

For passing data from C --> A use singleton pattern. any data you want to pass save in variable using singleton pattern and then use

 self.navigationController?.popToRootViewController(animated: true)

and now you can access data where you want. hope its help