Search code examples
iosxcodeswiftsegueuisplitviewcontroller

Trigger popover in DetailView from MasterView


I'm new to iOS programming (learning with Swift) and recently got interested into Master Detail Applications, as the current chapter of the book I'm learning with is about it, too.

I noticed that my book seems to be a little too old, because Xcode's template for Master Detail Apps brings in a Split View Controller while the template in the book still uses just a Navigation Controller as the initial ViewController:

Template from Xcode (Template from Xcode) Template from the book (Template from the book)

What I would like to do is place a "+" button in the toolbar of the Master View Controller that then triggers a full screen popup of another ViewController inside the Detail View Controller. See the contacts app as a reference, where exactly this happens if you run it in landscape on an iPad or iPhone Plus:

Example from contacts app (Example from the contacts app)

In the example of the book, there just was the "+" added to the toolbar, and a segue added from it to the new View Controller, but it's not as easy with Xcode's new template. How can I make such a popover in the Detail View, but initiated by a button in the Master View?

Thanks


Solution

  • Starting with the default MD template:

    • Remove addButton code from MasterViewController’s viewDidLoad.

    • Create an add button for the master in the storyboard and link it to a MasterViewController action.

    • Create a segue from your detail controller to the one you want to use as an overlay and give it a name.

    • Create a method in the detail controller that performs that segue.

    E.g.:

    func displayOverlay() {
        print("perform a segue here to the required controller")
        self.performSegueWithIdentifier("overlay", sender: self)
    }
    
    • In the master action, call the detail method to trigger the segue.

    E.g.:

    @IBAction func detailAdd(sender: AnyObject) {
        if let dvc : DetailViewController = detailViewController {
            dvc.displayOverlay()
        } else {
            print("Oops...no detail controller")
        }
    }
    

    You will have to do extra work if you want the animation styles that you're showing, but this should get you the basic controller connections.