Swift pass data through navigation controller
Override prepareForSegue
and set whatever value on the tableview you'd like. You can grab the tableview from the UINavigation
viewControllers
property.
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!){
let navVC = segue.destinationViewController as UINavigationController
let tableVC = navVC.viewControllers.first as YourTableViewControllerClass
tableVC.yourTableViewArray = localArrayValue
}
For Swift 3 :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navVC = segue.destination as? UINavigationController
let tableVC = navVC?.viewControllers.first as! YourTableViewControllerClass
tableVC.yourTableViewArray = localArrayValue
}
@Tommy Devoy's answer is correct but here is the same thing in swift 3
Updated Swift 3
// MARK: - Navigation
//In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "yourSegueIdentifier" {
if let navController = segue.destination as? UINavigationController {
if let chidVC = navController.topViewController as? YourViewController {
//TODO: access here chid VC like childVC.yourTableViewArray = localArrayValue
}
}
}
}
I was getting this error to Horatio's solution.
ERROR: Value of type 'UINavigationController' has no member 'yourTableViewArray'
So this might help others like me looking for a code
only solution. I wanted to redirect to a Navigation controller, yet pass data to root view controller within that Nav Controller.
if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourNavigationControllerID") as? UINavigationController,
let yourViewController = controller.viewControllers.first as? YourViewController {
yourViewController.yourVariableName = "value"
self.window?.rootViewController = controller // if presented from AppDelegate
// present(controller, animated: true, completion: nil) // if presented from ViewController
}