I am implementing a search interface for my application, so basically I will pass the search keyword from one ViewController to another ViewController.
I have done this type of parameter passing several times but something seems strange this time. The destination ViewController is embedded in a Navigation Controller.
Now the code looks something like this.
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject!) {
if (segue?.identifier == "home_to_search") {
var searchKeyword = txtSearchBarHome.text
var svc = segue?.destinationViewController as! SearchViewController;
svc.toPassSearchKeyword = searchKeyword;
//let nav = segue?.destinationViewController as! UINavigationController
//let svc = nav.topViewController as! SearchViewController
//svc.toPassSearchKeyword = searchKeyword;
}
}
I have already explored these questions DestinationViewController Segue and UINavigationController swift, How do I segue values when my ViewController is embedded in an UINavigationController? with no luck.
What makes me wonder is that I already have ViewControllers embedded in Navigation Controllers that I can pass parameters by segueing. However, in this case it throws a Could not cast value of type 'UINavigationController' error. If I try the commented code above it does not throw an error there, but at the AppDelegate class.
Answering my own question. In this case we need to access the child view by doing something like this:
let nav = segue?.destinationViewController as! UINavigationController
let svc = nav.topViewController as! SearchViewController
svc.toPassSearchKeyword = searchKeyword;
Based on Semih's answer, you can also do this to pass a variable to next segue if you don't want to use an identifier:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nav = segue.destination as? UINavigationController,
let vc = nav.topViewController as? TestViewController {
vc.username = "Test"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With