Search code examples
iosswiftuisplitviewcontrollermaster-detail

How to let UISplitViewController on Storyboard show master view first?


I have a simple app with a storyboard with just a split view controller freshly drag-dropped from the UI objects list.

When I start the app on an iPhone simulator, the detail view appears first.

How do I make sure that the master view is shown at app startup? Is there a way to arrange that on the storyboard?


Solution

  • In order to enable the master view to collapse on iPhone by default, override some delegate methods:

    class SplitViewController : UISplitViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            self.delegate = self
        }
    }
    
    extension SplitViewController : UISplitViewControllerDelegate {
    
        // The default for this is .secondary!!
        @available(iOS 14.0, *)
        public func splitViewController(_ svc: UISplitViewController, 
            topColumnForCollapsingToProposedTopColumn 
            proposedTopColumn: UISplitViewController.Column) -> UISplitViewController.Column {
            return .primary
        }
    
        // default is false!
        public func splitViewController(_ splitViewController: UISplitViewController,
                                 collapseSecondary secondaryViewController:UIViewController,
                                 onto primaryViewController:UIViewController) -> Bool {
            return true
        }
    }
    

    Previously you'd use preferredDisplayMode = .primaryOverlay, but this is now deprecated. The code works for iOS 14 and is backwards compatible for earlier iOS versions also.