[英]How to navigate and pass data between UIViewControllers whose layout resembles a fork?
I have a couple of UIViewControllers
like shown 我有几个如图所示的UIViewControllers
What I want is to pass data from B to C and also do that transition. 我想要的是将数据从B传递到C,然后执行该转换。 So far I've come with 2 possible solutions: 到目前为止,我提供了两种可能的解决方案:
UIViewController
class (and save a reference of the data in it), pop B from the navigation controller
and push C into it. 创建C UIViewController
类的新实例(并在其中保存数据引用),从navigation controller
弹出B并将C推入其中。 navigation controller
and then, in the viewWillAppear
method of A, check if the data is not nil to know if it should send it to C and perform the segue
. 将数据发送到A,从navigation controller
弹出B,然后在A的viewWillAppear
方法中检查数据是否为nil,以了解是否应将其发送给C并执行segue
。 Should I take any of those 2 approaches? 我应该采用这两种方法中的任何一种吗? Or is there a more elegant/proper solution for this situation? 还是针对这种情况有更优雅/合适的解决方案?
Thanks 谢谢
Organize data manager of parent controller or use Core Data. 组织上级控制器的数据管理器或使用核心数据。
In case of keeping data in parent controller, use dependency injection like described here 如果将数据保留在父控制器中,请使用此处所述的依赖项注入
Here is an example for your case: 这是您的情况的示例:
var dataFromC = "" // or nil
var dataFromB = "" // or nil
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "B",
let viewController = segue.destinationViewController as? BViewController {
viewController.dataFromC = self.dataFromC
// declare method in BViewController
// var method : ((String) -> ())? = nil
viewController.method = {[weak self] valueFromB in
self?.dataFromB = valueFromB
}
}
if segue.identifier == "C",
let viewController = segue.destinationViewController as? CViewController {
viewController.dataFromB = self.dataFromB
// declare method in CViewController
// var method : ((String) -> ())? = nil
viewController.method = {[weak self] valueFromC in
self?.dataFromC = valueFromC
}
}
}
If you want to pass value to parent controller from BViewController
, use self.method("yourValueFromB")
where you will change the value. 如果要从BViewController
将值传递给父控制器,请使用self.method("yourValueFromB")
在其中更改值。 For case with CViewController
use same approach. 对于CViewController
使用相同的方法。
As a general practice, B should send the data back to its originating view controller A with the help of delegate protocol pattern. 通常,B应该在委托协议模式的帮助下将数据发送回其原始视图控制器A。 A should be able to then decide in the delegate method implementation, what the data is received from B and where to send this data, which in this case is C. 然后,A应该能够在委托方法实现中决定从B接收什么数据以及将数据发送到哪里(在这种情况下为C)。
This way your code looks more organised. 这样,您的代码看起来更有条理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.