Reputation: 4101
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.
Upvotes: 20
Views: 20940
Reputation: 291
Just a quick note for those looking into this issue it has been renamed to Destination
let nav = segue.destination as! UINavigationController
let svc = nav.topViewController as! SearchViewController
svc.toPassSearchKeyword = searchKeyword;
Upvotes: 0
Reputation: 986
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"
}
}
Upvotes: 5
Reputation: 4101
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;
Upvotes: 61