从Table View Controller跳转至Tab Bar Controller传值时类型转换报错
Hey there, let's break down why you're hitting that cast error and fix it up!
问题根源
The error Could not cast value of type 'UIViewController' to 'DriesVD.PersoonViewController' tells us one key thing: the view controller at index 0 of your tab bar controller isn't directly your PersoonViewController.
Almost certainly, you've wrapped PersoonViewController in a UINavigationController inside your Storyboard (a super common setup to add navigation bar functionality). So when you try to cast tabCtrl.viewControllers![0] directly to PersoonViewController, you're actually trying to cast a UINavigationController to your custom VC type—hence the crash.
修正后的代码
Here's how to adjust your prepare(for:sender:) method to handle this correctly, plus we'll add safer optional binding to avoid those risky force unwraps (!):
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "naarPersoonView" else { return } // First get the tab bar controller from the segue destination guard let tabCtrl = segue.destination as? UITabBarController else { print("Could not cast destination to UITabBarController") return } // Get the first child controller of the tab bar—this is likely a UINavigationController guard let navCtrl = tabCtrl.viewControllers?.first as? UINavigationController else { print("First tab controller is not a UINavigationController") return } // Now get the root view controller of the navigation controller, which is your PersoonViewController guard let persoonVC = navCtrl.rootViewController as? PersoonViewController else { print("Could not cast root VC to PersoonViewController") return } // Safely get the selected row and pass the person object guard let indexPath = tableView.indexPathForSelectedRow else { return } persoonVC.persoon = personen[indexPath.row] }
额外检查步骤
- Double-check your Storyboard structure: Select your Tab Bar Controller, then look at its first child—if it's a Navigation Controller, then its root view controller should be your
PersoonViewController. - Make sure the custom class for your
PersoonViewControlleris correctly set in the Storyboard (go to the Identity Inspector and verifyDriesVD.PersoonViewControlleris selected).
内容的提问来源于stack exchange,提问作者DriesVD

