concept modal segue in category ios

appears as: modal segue, modal segue
iOS Development with Swift

This is an excerpt from Manning's book iOS Development with Swift.

  • Tap the plus button in the navigation bar. The book detail view controller should slide in from the right, with a back button on the left of the navigation bar (see figure 9.17). The show segue is most appropriate for content that provides more details about the user’s selection. When adding content, a modal segue is more appropriate. Rather than adding the new view controller to the navigation stack, a modal segue replaces the current view controller, displaying the new view controller over the top.
  • If you run the app now, you’ll find that the Cancel and Save buttons no longer dismiss the view controller. The dismiss method is appropriate for when a view controller has been presented, such as via a modal segue. The show segue pushes the view controller onto the navigation stack. When a view controller in a navigation stack wants to be removed, it needs to request this from the navigation controller, using the popViewController method.

  • Check the presentingViewController property and dismiss the view controller appropriately:
    func dismissMe() {
        if presentingViewController != nil {                             1
            // was presented via modal segue
           dismiss(animated: true, completion: nil)                      2
        } else {                                                         3
            // was pushed onto navigation stack
            navigationController!.popViewController(animated: true)      4
        }
    }
    • 1 If presented
    • 2 Dismisses view controller
    • 3 If pushed
    • 4 Pops view controller
    Similar to the way you can remove view controllers in code, they can also be displayed in code, rather than using storyboard segues. Table 9.1 shows the segues and their related methods.
    Table 9.1. Displaying and removing a view controller

    Managed by

    Equivalent segue

    Method to display

    Method to remove

    Navigation controller Show pushViewController popViewController
    View controller Modal/Popover present dismiss
  • func dismissMe() {
        if presentingViewController != nil {                             1
            // was presented via modal segue
           dismiss(animated: true, completion: nil)                      2
        } else {                                                         3
            // was pushed onto navigation stack
            navigationController!.popViewController(animated: true)      4
        }
    }
    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest