iosswiftuikituisplitviewcontroller

Reliably knowing when UISplitViewController shows the primary view


I have an app which supports both iPhone and iPad, and it uses an embedded UISplitViewController.

I'd like to manually control the sidebar visibility, so I have added a button to toggle it on/off. However, it turns out that iPhone and iPad treat the values differently.

On iPad, you can check the value of .displayMode to see if the split view is only presenting the secondary view:

if editorSplitView.displayMode == .secondaryOnly { // ...

But this does not work on iPhone, which always says the display mode is .oneBesideSecondary, no matter the setup. Even when the primary view is open, the value stays the same on iPhone. Checking splitView.isCollapsed doesn't help either, as on a smaller screen either view is collapsed at all times anyway.

Based on the docs this is the intended behavior:

When collapsed is YES, the value of this property is ignored. A collapsed split view interface contains only one view controller, so the display mode is superfluous.

... but doesn't really tell me how to determine which view is visible.

I know that implementing your own show/hide button is somewhat unorthodox but I have a justified use case. What's the actual, preferred way to know the display mode on both devices?


Solution

  • You don't need to use any split view controller methods for this. You can use the most basic way of checking if a view controller is visible:

    if splitViewController.viewControllers.first?.viewIfLoaded?.window == nil {
        // The view is not visible
    }