snapchatdotcom snapchatdotcom - 3 months ago 17
Swift Question

SplitViewController is expected to have a view controller at index 0 before it used?

I keep getting this error in the console every time I display my split view controller. I couldn't find a concrete solution on this? Guidance?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
let splitViewController = UISplitViewController()
let masterViewController = TabBarMaster(collectionViewLayout: UICollectionViewFlowLayout())
let detailViewController = UINavigationController()

splitViewController.maximumPrimaryColumnWidth = 80

splitViewController.preferredDisplayMode = .AllVisible
splitViewController.delegate = self
splitViewController.viewControllers = [masterViewController, detailViewController]
window?.rootViewController = splitViewController

return true
}

Answer

Set the splitViewController viewControllers array before setting any other properties of splitViewController:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    window = UIWindow(frame: UIScreen.mainScreen().bounds)
    window?.makeKeyAndVisible()
    let splitViewController = UISplitViewController()
    let masterViewController = TabBarMaster(collectionViewLayout: UICollectionViewFlowLayout())
    let detailViewController = UINavigationController()

    splitViewController.viewControllers = [masterViewController, detailViewController] // move it here

    splitViewController.maximumPrimaryColumnWidth = 80
    splitViewController.preferredDisplayMode = .AllVisible
    splitViewController.delegate = self
    window?.rootViewController = splitViewController

    return true
}