SamiAlualy
SamiAlualy

Reputation: 51

How to pass data back to the first view controller in Swift?

I have two view controllers and I have this code to navigate between the 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 to send some data to the first view before popping it ?

Upvotes: 4

Views: 4069

Answers (1)

Snowman
Snowman

Reputation: 32061

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 just 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 popping, you'd do something like:

func goToFirstViewController() {
  let a = self.navigationController.viewControllers.first as! A
  a.data = "data"
  self.navigationController.popToRootViewControllerAnimated(true)
}

(haven't compiled the above)

Upvotes: 4

Related Questions