Master-detail view which is not initial in Swift

951 views Asked by At

I'm new to Swift.

I want to build a Master-detail view which is not initial of the app. The AppDelegate.swift generated by Xcode using Master-detail Application just go crash when I set other view before the Master-detail view.

Here's the code of AppDelegate.swift:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        let splitViewController = self.window!.rootViewController as! UISplitViewController
        let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
        navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
        splitViewController.delegate = self

        let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController
        let controller = masterNavigationController.topViewController as! MasterViewController
        controller.managedObjectContext = self.managedObjectContext
        return true
    }

And I got the following error:

Could not cast value of type 'UIViewController' (0x11079e418) to 'UISplitViewController' (0x1107a8eb8).
(lldb) 

And my Main.storyboard:

Main.storyboard

Thanks for help!

3

There are 3 answers

2
theMikeSwan On

Your initial view controller is a UIViewController but in the beginning of application(application:, didFinishLaunchingWithOptions:) you are still acting as though the first view onscreen is a UISplitViewController (see let splitViewController = self.window!.rootViewController as! UISplitViewController ).

In order to have a different view be the initial view controller you need to update that code appropriately to handle the different view controller being first.

2
Levi On

That is normal, since you are trying to cast a UIViewController to a UISplitViewController in this line:

let splitViewController = self.window!.rootViewController as! UISplitViewController

You either have to set the split as your initial view controller, or change the code and handle the root as a normal UIViewController.

0
Alan O'Regan On

I have the same problem. I think the answer is that if you are intending to start the storyboard with a View Controller rather than the Split View Controller then the initial template selected for setting up the project should be Single View application rather than Master-Detail application.