Swift – Hiding the master view controller with UISplitViewController in iOS8

ios8objective cswiftuisplitviewcontroller

I have an iOS7 application, which was based on the Xcode master-detail template, that I am porting to iOS8. One area that has changed a lot is the UISplitViewController.

When in portrait mode, if the user taps on the detail view controller, the master view controller is dismissed:

enter image description here

I would also like to be able to programmatically hide the master view controller if the user taps on a row.

In iOS 7, the master view controller was displayed as a pop-over, and could be hidden as follows:

[self.masterPopoverController dismissPopoverAnimated:YES];

With iOS 8, the master is no longer a popover, so the above technique will not work.

I've tried to dismiss the master view controller:

self.dismissViewControllerAnimated(true, completion: nil)

Or tell the split view controller to display the details view controller:

self.splitViewController?.showDetailViewController(bookViewController!, sender: self)

But nothing has worked so far. Any ideas?

Best Answer

Extend the UISplitViewController as follows:

extension UISplitViewController {
    func toggleMasterView() {
        let barButtonItem = self.displayModeButtonItem()
        UIApplication.sharedApplication().sendAction(barButtonItem.action, to: barButtonItem.target, from: nil, forEvent: nil)
    }
}

In didSelectRowAtIndexPath or prepareForSegue, do the following:

self.splitViewController?.toggleMasterView()

This will smoothly slide the master view out of the way.

I got the idea of using the displayModeButtonItem() from this post and I am simulating a tap on it per this post.

I am not really happy with this solution, since it seems like a hack. But it works well and there seems to be no alternative yet.

Related Topic