How can I pass data back to the first view controller in Swift?
I have two view controllers and I have this code to navigate between two views
ViewController:
func goToSecondViewController() {
let aa = self.storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as SecondViewController
self.navigationController.pushViewController(aa, animated: true)
}
/
SecondViewController:
func goToFirstViewController() {
self.navigationController.popToRootViewControllerAnimated(true)
}
How do I send some data in the first view before putting it out?
+3
source to share
1 answer
If A is a view controller with the following declaration:
class A : UIViewController {
var data: String!
}
Then, whenever you have an instance of A, you can simply set the data property directly:
let a = A() // assuming you've defined the init method
a.data = "hello"
Edit
If you want to send data before appearing, you should do something like:
func goToFirstViewController() {
let a = self.navigationController.viewControllers.first as! A
a.data = "data"
self.navigationController.popToRootViewControllerAnimated(true)
}
(did not compile above)
+4
source to share