Carlos Salame
Carlos Salame

Reputation: 43

Could not cast value of type 'UINavigationController' (0x10426be10)

i am very new to coding and i am doing a tutorial but I keep on getting this bug. Not sure what to do. I have been looking for answers for over an hour. Hope anyone here can help thanks.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)!
    let contact = self.contacts[indexPath.row]
    let destination = segue.destination as! DetailViewController
    destination.contact = contact
}

My MainStoryBoard: enter image description here

Upvotes: 0

Views: 1086

Answers (3)

Mannopson
Mannopson

Reputation: 2684

Try something like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

if segue.identifier == "yourIdentifier" {

 let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)! 
 let contact = self.contacts[indexPath.row] 
 let destination = segue.destination as! UINavigationController 
 let vc = destination.topViewController as! DetailViewController 
 vc.contact = contact 

    }
 }

Also make sure your segue identifier is defined

Upvotes: 1

Hexfire
Hexfire

Reputation: 6058

Here:

let destination = segue.destination as! DetailViewController

You are trying to cast UINavigationController to DetailViewController. This cannot be accomplished. DetailViewController (from your screenshot) is managed by UINavigationController, which is a direct destination in your case.

So the best practice would be wrapping your initial controller into UINavigationController, i.e. just make Navigation Controller the starting point of your app and then draw segue from table to DetailViewController (not into intermediate navigation controller). After that, your code will be working just fine.

Upvotes: 0

Andrea
Andrea

Reputation: 26385

Most probably, your segue is trying to show a UINavigationController with inside your DetailViewController.
Try to do that:

let destination = (segue.destination as! UINavigationController).rootViewController as! DetailViewController

Upvotes: 0

Related Questions