Swift:准备与导航控制器的Segue
我正在Swift中开发一个iOS应用程序。
我想使用prepareForSegue函数将数据从一个视图发送到另一个视图。
但是,我的目标视图之前是一个导航控制器,所以它不起作用。
我怎样才能做到这一点?
在prepareForSegue
访问目标导航控制器,然后在其顶部:
let destinationNavigationController = segue.destinationViewController as UINavigationController let targetController = destinationNavigationController.topViewController
Swift 3.0
let destinationNavigationController = segue.destination as! UINavigationController let targetController = destinationNavigationController.topViewController
从目标控制器,您可以访问其视图并传递数据。
假设您想要将数据从SendViewController发送到ReceiveViewController:
-
将此添加到SendViewController
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueShowNavigation"{ var DestViewController = segue.destinationViewController as! UINavigationController let targetController = DestViewController.topViewController as! ReceiveViewController targetController.data = "hello from ReceiveVC !" }}
-
将标识符segue编辑为“showNavigationController”
- 在你的ReceiveViewController中添加
这个
var data : String = "" override func viewDidLoad() { super.viewDidLoad() println("data from ReceiveViewController is \(data)") }
当然,你可以发送任何其他types的数据(int,Bool,JSON …)
使用optional binding
和Swift 3完成答案:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navigationViewController = segue.destination as? UINavigationController, let myViewController = navigationVC.topViewController as? MyViewControllerClass { myViewController.yourProperty = myProperty } }
Swift 3的答案如下:
let svc = segue.destination as? UINavigationController let controller: MyController = svc?.topViewController as! MyController controller.myProperty = "Hi there"
Swift 3中的一个class轮:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination.childViewControllers[0] as? FooController { vc.variable = localvariable } }