TRG TRG - 10 months ago 59
iOS Question

Master - Detail project not working as expected

Using the default project from xcode for a master-detail application, if i place a

debug statement in the collapse delegate, it never seems to get triggered when i rotate the device (in fact i can't get it too trigger ever).

The bit of code i've edited is in AppDelegate.swift and looks like this

func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {


guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
return false

and as you can see the delegate is set correctly as per the default project:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> 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
return true

The only thing changed from the default project is that
line i've added.

It's my understanding that when it collapses the split view (i.e. due to rotation from landscape to portrait) it should call this delegate method to work out which detail view to use... However it never calls that delegate method.

Am i just not getting how this works or is the default project itself broken?

My end goal is too make it so the master view (on the left) becomes the primary view when it collapses if the detail view has a certain variable set to nil. Getting this (and other delegate methods) to trigger I guess is the first stage of achieving this.

dan dan
Answer Source

The delegate methods concerning collapsing/expanding/separating are called during size class changes that happen during split screen multitasking on iPad or when using a split view controller on iPhone.

Hiding/showing the master view controller is a result of the split view controller's displayMode changing which you can react to in the splitViewController:willChangeToDisplayMode: delegate method.