无法将类型 'UINavigationController' (0x10836e698) 的值转换为 'UITabBarController' (0x10836e6e8)。?

Could not cast value of type 'UINavigationController' (0x10836e698) to 'UITabBarController' (0x10836e6e8).?

这是我试图在其中打开 splitviewcontroller 的 UITabBarController 的代码。

import UIKit

class SecondViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

}

override func viewDidAppear(animated: Bool) {

super.viewDidAppear(animated)

///在这一行之后出现错误

var mainCont : UITabBarController = ((UIApplication.sharedApplication().delegate) as! AppDelegate).window?.rootViewController as! UITabBarController

var navCont2 : UINavigationController? = mainCont.viewControllers?[1] as? UINavigationController

var controller = UIStoryboard(name: "Storyboard2", bundle: nil).instantiateInitialViewController() as! UISplitViewController

controller.preferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible

navCont2?.presentViewController(controller, animated: true, completion: nil)

}

 override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

}

你的第一行:

var mainCont : UITabBarController = ((UIApplication.sharedApplication().delegate) 
    as! AppDelegate).window?.rootViewController as! UITabBarController

正在将 window 的 rootViewController 作为 UITabBarController。错误信息真的很清楚:

Could not cast value of type 'UINavigationController' (0x10836e698) to 'UITabBarController' (0x10836e6e8).

在应用程序启动时,window 的 rootViewController 设置为您在 Storyboard 上定义的初始视图控制器(大灰色箭头)。我的猜测是您的初始视图控制器设置为 UINavigationController,但在您的代码中您试图将其强制转换为 UITabBarController.