You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Table View Controller跳转至Tab Bar Controller传值时类型转换报错

解决Segue跳转传值时的类型转换错误

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 PersoonViewController is correctly set in the Storyboard (go to the Identity Inspector and verify DriesVD.PersoonViewController is selected).

内容的提问来源于stack exchange,提问作者DriesVD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:35:05