Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not cast value of type 'UINavigationController'

Tags:

xcode

swift

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.

like image 513
Semih Yagcioglu Avatar asked May 13 '15 08:05

Semih Yagcioglu


2 Answers

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;
like image 179
Semih Yagcioglu Avatar answered Sep 23 '22 21:09

Semih Yagcioglu


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"
    }
}
like image 23
Json Avatar answered Sep 20 '22 21:09

Json