简体   繁体   English

在控制器 ABC 之间传递数据,从 C 到 A

[英]Passing data between controllers ABC, from C to A

Consider three different controllers A, B and C where A is initial controller in Navigation Controller.考虑三个不同的控制器 A、B 和 C,其中 A 是导航控制器中的初始控制器。

Now I push to B and then push to C.现在我推到 B,然后推到 C。

A --> B --> C

Then I want to go from C to A. How can I go there with a single push and animation.然后我想从C转到A。我怎么能用一个推和动画去那里。 I guess the way would be finding the controller A from the navigation stack and call popToController method.我想方法是从导航堆栈中找到控制器 A 并调用popToController方法。 Let me know If any other better way.如果有其他更好的方法,请告诉我。

Now main question is how can I pass the data from C --> A .现在的主要问题是如何从C --> A传递数据。 If it's from B --> A I could use the delegation.如果它来自B --> A我可以使用委托。 But for C --> A what could be done to use the delegation?但是对于C --> A什么委托可以做什么?

I do have workaround by using observer, singleton, reactive patterns.我确实有使用观察者、单例、反应模式的解决方法。 But I would like to know if any better way can be used.但我想知道是否可以使用更好的方法。

You can have multiple ways to achieve this functionality.您可以通过多种方式来实现此功能。 Once can be get you VC from list and pop to it.一次可以从列表中获取 VC 并弹出到它。

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 .你也可能对unwind segue感兴趣。 Here is a nice example too. 这里也是一个很好的例子。

You can achieve this via this approach, it will work 100%您可以通过这种方法实现这一点,它将 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)
        }
    }

For passing data from C --> A use singleton pattern.用于从 C 传递数据 --> A 使用单例模式。 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希望它的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM